package com.goldcn.order.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goldcn.b2b.service.ClassifyDiscountService;
import com.goldcn.cart.dao.GoodsCartMapper;
import com.goldcn.cart.dto.GoodsCartDto;
import com.goldcn.cart.service.GoodsCartService;
import com.goldcn.common.*;
import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.model.DataResult;
import com.goldcn.common.util.CodeGenerator;
import com.goldcn.common.util.CommonUtils;
import com.goldcn.common.util.IdGen;
import com.goldcn.config.Constants;
import com.goldcn.config.ErpInterfaceCfg;
import com.goldcn.config.ProConstants;
import com.goldcn.enumeration.ErpInterfaceCfgEnum;
import com.goldcn.enumeration.PayFeeEnum;
import com.goldcn.enumeration.PointCfgEnum;
import com.goldcn.goods.dao.GoodsInfoMapper;
import com.goldcn.goods.dao.GoodsSkuMapper;
import com.goldcn.goods.dao.GoodsSkuShopMapper;
import com.goldcn.goods.dto.GoodsInfoWithSkuDto;
import com.goldcn.goods.dto.QueryGoodsSkuRateDto;
import com.goldcn.goods.model.GoodsInfo;
import com.goldcn.goods.model.GoodsSku;
import com.goldcn.goods.model.GoodsSkuShop;
import com.goldcn.goods.service.GoodsClassifyCommissionService;
import com.goldcn.goods.service.GoodsService;
import com.goldcn.interceptor.SystemContext;
import com.goldcn.order.controller.OrderController;
import com.goldcn.order.dao.*;
import com.goldcn.order.dto.*;
import com.goldcn.order.erpVo.ResultData;
import com.goldcn.order.erpVo.*;
import com.goldcn.order.model.*;
import com.goldcn.order.vo.*;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.Doubles;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.codec.Charsets;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by admin on 2016/11/16.
 */
@Service
@Transactional
@ConfigurationProperties("bank")
public class OrderService {


    //云管控按品类查子类
    private String classifySearchByIdUrl;

    //用户数据库表配置
    private String databaseTableUser;

    @Autowired
    OrderInfoMapper orderInfoMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderLogisticsMapper orderLogisticsMapper;

    @Autowired
    OrderSnapshotMapper orderSnapshotMapper;

    @Autowired
    OrderSettlementMapper orderSettlementMapper;

    @Autowired
    OrderSupplierSettlementMapper orderSupplierSettlementMapper;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    GoodsInfoMapper goodsInfoMapper;

    @Autowired
    GoodsService goodsService;

    @Autowired
    GoodsCartMapper goodsCartMapper;

    @Autowired
    GoodsSkuMapper goodsSkuMapper;

    @Autowired
    GoodsCartService goodsCartService;

    @Autowired
    GoodsClassifyCommissionService goodsClassifyCommissionService;

    @Autowired
    OrderIndexService orderIndexService;

    @Autowired
    OrderBankSettlementMapper orderBankSettlementMapper;

    @Autowired
    ErpInterfaceCfg erpInterfaceCfg;

    @Autowired
    OrderAddressMapper orderAddressMapper;

    @Autowired
    ErrErpOrderMapper errErpOrderMapper;

    @Autowired
    CommissionUserService commissionUserService;
    @Autowired
    ClassifyDiscountService classifyDiscountService;

    @Autowired
    GoodsSkuShopMapper goodsSkuShopMapper;

    private static Logger logger = LoggerFactory.getLogger(OrderService.class);

    private static final String GROUP = "orderService";
    //重复通知过滤
    private static ExpireKey expireKey = new DefaultExpireKey();


    private static String openGoldPoint = null;

    public static String isOpenErp = null;

    private static String openPointDeduction = null;


    public String getDatabaseTableUser() {
        return databaseTableUser;
    }


    public void setDatabaseTableUser(String databaseTableUser) {
        this.databaseTableUser = databaseTableUser;
    }


    private Integer getUserType(Long userID) {
        DataResult userResult = HttpUtil.httpGet(ProConstants.getUserByID + userID, restTemplate);
        if (!Objects.equal(userResult.getIsSuccess(), 1)) {
            throw new ServiceException("调用base服务失败");
        }
        if (userResult.getData() == null) {
            throw new ServiceException("未获取到用户信息");
        }
        Map<String, Object> userinfo = (Map<String, Object>) userResult.getData();
        return MapUtils.getInteger(userinfo, "type");
    }

    public Object addOrder(List<AddOrderDto> addOrderDtoList, boolean isB2b) throws Exception {

        Map<Long, Long> param = new HashMap<Long, Long>();
        List<Long> cartIDList = new ArrayList<Long>();
        Long orderID = null;
        String mobile = null;
        Map<String, Object> paraPoint = null;
        BigDecimal pointAmount = BigDecimal.ZERO;
        Map<Long, Double> pointAmountForComMap = Maps.newHashMap();

        String key = "newOrder-";

        //供应商成本 add by pengzh 2018-3-26
        BigDecimal dueAmount = BigDecimal.ZERO;


        //优惠券总金额
        BigDecimal discountAmount = BigDecimal.ZERO;
        //优惠券领用ID
        Long couponID = 0l;

        int discountWay = 0;

        /*for start*/
        boolean goldPriceChangeFlag = true;
        Long selID;
        for (AddOrderDto addOrderDto : addOrderDtoList) {
            double pointAmountForCom = 0d;
            key = key + addOrderDto.getCartID() + addOrderDto.getUserID();
            if (expireKey.exists(key)) {
                throw new ServiceException("您刚刚已经提交了，请勿重复操作");
            } else {
                expireKey.add(key);
            }
            GoodsCartMore goodsCart = new GoodsCartMore();
            GoodsCartDto goodsCart1 = goodsCartService.querySingleMyShoppingCart(addOrderDto.getCartID());
            BeanUtils.copyProperties(goodsCart, goodsCart1);
            goodsCart.setGoodsName(goodsCart1.getName());
            goodsCart.setAddressID(addOrderDto.getAddressID());
            if (addOrderDto.getInvoices() == 2) {
                if (StringUtils.isEmpty(addOrderDto.getInvoicesHead())) {
                    throw new ServiceException("请填写发票抬头", RestConst.ErrorCode.FORM_FAIL);
                }
            }

            goodsCart.setInvoices(addOrderDto.getInvoices());
            goodsCart.setInvoicesHead(addOrderDto.getInvoicesHead());
            goodsCart.setInvoicesNO(addOrderDto.getInvoicesNO());//纳税人识别号

            if (goodsCart.getQty() <= 0) {
                throw new ServiceException(goodsCart.getGoodsName() + "商品数量必须大于0", RestConst.ErrorCode.FORM_FAIL);
            }
            if (goodsCart.getState() == 0) {
                throw new ServiceException(goodsCart.getGoodsName() + "购物车商品已经失效", RestConst.ErrorCode.FORM_FAIL);
            }
            //优惠类型: 1:金豆 2:优惠券,default:1
            if ("2".equals(addOrderDto.getCouponType()) && addOrderDto.getPointAmount().compareTo(BigDecimal.ZERO) == 1) {
                discountAmount = addOrderDto.getPointAmount();
                couponID = addOrderDto.getCouponID();
                if (couponID == null) {
                    logger.error("优惠券领用ID未指定");
                }
            }
            //获取用户下单所需用户及其组织信息
            UserInfoForOrderDto userInfoForOrderDto = (UserInfoForOrderDto) getUserInfoForOrder(goodsCart.getUserID());

            //
            if (param.get(goodsCart.getSellerID()) == null) {
                OrderInfo orderInfo = new OrderInfo();

                orderInfo.setOrderID(IdGen.get().nextId());
                orderInfo.setOrderNO(CodeGenerator.INSTANCE.nextId());
                orderInfo.setState(1);
                orderInfo.setAddTime(CommonUtils.getCurTimestamp());
                orderInfo.setInvoices(goodsCart.getInvoices());
                orderInfo.setInvoicesHead(goodsCart.getInvoicesHead());
                orderInfo.setAddressID(goodsCart.getAddressID());  //这里修改 需要通过addressID查询地址信息 然后得到新添加的三个字段的值
                orderInfo.setPayType(1);
                orderInfo.setInvoicesType(goodsCart.getInvoicesType());
                orderInfo.setInvoicesNO(goodsCart.getInvoicesNO());

                orderInfo.setShopID(addOrderDto.getShopID());
                orderInfo.setStoreManagerID(getStoreManagerByUserID(addOrderDto.getUserID()));


                String url = ProConstants.getAddress + goodsCart.getAddressID();
                DataResult result = HttpUtil.httpGet(url, restTemplate);
                if (result.getIsSuccess() == 1) {
                    Map<String, Object> mapResult = (Map<String, Object>) result.getData();
                    if (mapResult != null) {
                        orderInfo.setReceiverAddress(mapResult.get("address").toString());
                        orderInfo.setReceiverName(mapResult.get("contacts").toString());
                        orderInfo.setReceiverPhone(mapResult.get("contactPhone").toString());

                        OrderAddress orderAddress = new OrderAddress();
                        orderAddress.setAddressId(IdGen.get().nextId());
                        orderAddress.setOrderId(orderInfo.getOrderID());
                        orderAddress.setProvince((int) mapResult.get("province"));
                        orderAddress.setCity((int) mapResult.get("city"));
                        orderAddress.setDistrict((int) mapResult.get("district"));
                        orderAddressMapper.insertSelective(orderAddress);
                    }
                } else {
                    orderInfo.setReceiverAddress("无信息");
                    orderInfo.setReceiverName("无信息");
                    orderInfo.setReceiverPhone("无信息");
                }

                orderInfo.setSellerID(goodsCart.getSellerID());
                orderInfo.setSellerName(goodsCart.getSellerName());
                orderInfo.setUserID(goodsCart.getUserID());
                //增加公司id by pengzh 2017-7-11
                orderInfo.setCompanyID(SystemContext.getCompanyID());

                //增加使用金豆,优惠策略 added by tim peng 2017-4-5, 保存金豆信息，并抵扣 2017-5-12
                orderInfo.setCouponType(addOrderDto.getCouponType());
                orderInfo.setPointQty(addOrderDto.getPointQty());
                orderInfo.setPointAmount(addOrderDto.getPointAmount());
                if (!isOpenGoldPoint() && "1".equals(addOrderDto.getCouponType())) {
                    orderInfo.setPointQty(BigDecimal.ZERO);
                    orderInfo.setPointAmount(BigDecimal.ZERO);
                }
                if (orderInfo.getPointQty() == null) {
                    orderInfo.setPointQty(BigDecimal.ZERO);
                }
                if (orderInfo.getPointAmount() == null) {
                    orderInfo.setPointAmount(BigDecimal.ZERO);
                } else {
                    pointAmount = orderInfo.getPointAmount();
                    if (pointAmount.compareTo(BigDecimal.ZERO) == 1 && "1".equals(addOrderDto.getCouponType())) {
                        paraPoint = new HashMap<String, Object>();
                        paraPoint.put("amount", pointAmount);
                        paraPoint.put("point", orderInfo.getPointQty());
                        paraPoint.put("userID", orderInfo.getUserID());
                        paraPoint.put("payNo", orderInfo.getOrderNO());
                    }
                }
                //获取用户下单所需用户及其组织信息
                mobile = userInfoForOrderDto.getMobile();
                orderInfo.setUserName(userInfoForOrderDto.getUserName());
                orderInfo.setSalesManagerID(userInfoForOrderDto.getSalesManagerID());
                orderInfo.setSalesID(userInfoForOrderDto.getSalesID());
                orderInfo.setBranchID(userInfoForOrderDto.getBranchID());
                orderInfo.setTwoLevelBranchID(userInfoForOrderDto.getTwoLevelBranchID());
                orderInfo.setSubbranchID(userInfoForOrderDto.getSubbranchID());

                //小商城存在多个商城切换， 结构信息存购买商城层级 2018-4-8
                if (!isB2b) {
                    Map<String, Object> mallInfo = getMallInfo(addOrderDto.getShopID());
                    Integer distGrade = MapUtils.getInteger(mallInfo, "level");
                    switch (distGrade.intValue()) {
                        case 2:
                            //一级代理
                            orderInfo.setBranchID(MapUtils.getLong(mallInfo, "oID"));
                            break;
                        case 3:
                            //二级代理
                            orderInfo.setBranchID(MapUtils.getLong(mallInfo, "branchID"));//分部
                            orderInfo.setTwoLevelBranchID(MapUtils.getLong(mallInfo, "oID"));//二级分部
                            break;
                        case 4:
                            //三级代理
                            orderInfo.setBranchID(MapUtils.getLong(mallInfo, "branchID"));//分部
                            orderInfo.setTwoLevelBranchID(MapUtils.getLong(mallInfo, "twoLevelBranchID"));//二级分部
                            orderInfo.setSubbranchID(MapUtils.getLong(mallInfo, "oID"));//支部
                            break;
                        case 1:
                            //0级
                            throw new ServiceException("当前商城资料有误，不支持");
                    }
                }


                if (pointAmount != null && pointAmount.compareTo(BigDecimal.ZERO) == 1 && !isOpenPointDeduction() && "1".equals(addOrderDto.getCouponType())) {
                    throw new ServiceException("您选择的金豆抵现活动已下线,请重新选择或更新版本", RestConst.ErrorCode.DATABASE_ERROR);
                }
                //  添加线下支付 线下支付 add buyadong 2017-6-14 10:00:49
                if (addOrderDto.getOrderPayType() != null && addOrderDto.getOrderPayType() == 1) {
                    //orderPaytype =1 线下支付
                    orderInfo.setOrderPayType(addOrderDto.getOrderPayType());
                    //orderInfo.setPayTime(CommonUtils.getCurTimestamp());
                    orderInfo.setCheckCode(getRandByNum(4));//核销码
                    orderInfo.setPayNo(orderInfo.getOrderNO());// payno = orderno added by pengzh 17-8-9
                    orderInfo.setCheckInvalidTime(DateUtils.addDays(new Date(), +7).getTime());//失效时间
                }
                orderInfo.setCompanyID(SystemContext.getCompanyID());

                orderInfoMapper.insertSelective(orderInfo);

                //将sellerID与oID插入map
                param.put(goodsCart.getSellerID(), orderInfo.getOrderID());
                orderID = orderInfo.getOrderID();
                selID = orderInfo.getSellerID();
            } else {
                orderID = param.get(goodsCart.getSellerID());
                selID = orderID;
            }
            OrderItem orderItem = new OrderItem();
            orderItem.setItemID(IdGen.get().nextId());
            orderItem.setOrderID(orderID);
            orderItem.setQty(goodsCart.getQty());
            orderItem.setSkuID(goodsCart.getSkuID());
            orderItem.setGoodsID(goodsCart.getGoodsID());
            orderItem.setGoodsName(goodsCart.getGoodsName());

            GoodsInfoWithSkuDto goodsInfoWithSkuDto = new GoodsInfoWithSkuDto();

            Long VipPriceSW = getVipPriceSW(SystemContext.getCompanyID());//获取开关
            boolean bocgold = getBocgold();
            boolean isOpenCom = commissionUserService.isClazzSupply(SystemContext.getCompanyID(), restTemplate)
                    && commissionUserService.isAdmin(addOrderDto.getUserID()) && goodsService.isActiveAdmin(addOrderDto.getUserID());
            if (bocgold && addOrderDto.getDiscountType() != null && addOrderDto.getDiscountType() == 0) {
                VipPriceSW = 1L;
            }
            if (isB2b) {
                goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuIDv2(goodsCart.getSkuID(), 0l);
            } else {
                goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuIDvShop(goodsCart.getSkuID(), 0l, addOrderDto.getShopID());
            }
            GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(goodsCart.getGoodsID());
            //add by lmn
            if (goodsInfo.getPriceType() == 1) {
                BigDecimal pri = null;

                if (isB2b) {
                    pri = goodsService.getTodayGoldPriceByOtherFee(goodsInfo.getSupplierID(), goodsInfo.getAttr(), goodsInfoWithSkuDto.getAttrJson(), goodsInfoWithSkuDto.getPrice());
                } else {
                    GoodsSkuShop skuShop = goodsSkuShopMapper.selectBySkuIDAndShopID(goodsCart.getSkuID(), addOrderDto.getShopID());
                    pri = goodsService.getTodayGoldPriceByOtherFee(goodsInfo.getSupplierID(), goodsInfo.getAttr(), goodsInfoWithSkuDto.getAttrJson(), skuShop.getOtherFee());
                }
                orderItem.setRetailPrice(pri);
                orderItem.setPrice(pri);
               /* if (goldPriceChangeFlag) {
                    goldPriceChangeFlag = pri.compareTo(addOrderDto.getPrice()) == 0 ? true : false;
                }*/
            } else {
                orderItem.setRetailPrice(goodsInfoWithSkuDto.getPrice());
                orderItem.setPrice(goodsInfoWithSkuDto.getPrice());
            }

            if (null != addOrderDto.getUserID() && 2 == VipPriceSW && goodsInfo.getPriceType() == 0) {//会员价
                goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuIDv2(goodsCart.getSkuID(), userInfoForOrderDto.getVipLevel());
                orderItem.setRetailPrice(goodsInfoWithSkuDto.getVipPrice());
                /*discountWay = 1;*/
                if (userInfoForOrderDto.getType() == 3 || userInfoForOrderDto.getType() == 4) {
                    discountWay = 1;
                }
            }
            if (!goodsInfoWithSkuDto.getState().equals("Shelve")) {
                throw new ServiceException("商品已失效，不能购买", RestConst.ErrorCode.DATABASE_ERROR);
            }
            if (goodsInfoWithSkuDto.getInventory() < goodsCart.getQty()) {
                throw new ServiceException("库存不足！", RestConst.ErrorCode.DATABASE_ERROR);
            }

            //丝绸之路商品不参与抵扣 added by tim peng 2017-5-24
            if ("0".equalsIgnoreCase(goodsInfoWithSkuDto.getGoodsID() + "") && pointAmount != null && pointAmount.compareTo(BigDecimal.ZERO) == 1) {
                throw new ServiceException("此商品不参与抵现", RestConst.ErrorCode.FORM_FAIL);
            }
            if (pointAmount != null && pointAmount.compareTo(BigDecimal.ZERO) == 1 && !isOpenPointDeduction() && "1".equals(addOrderDto.getCouponType())) {
                throw new ServiceException("您选择的金豆抵现活动已下线,请重新选择或更新版本", RestConst.ErrorCode.DATABASE_ERROR);
            }
            orderItem.setGoodsImg(goodsInfoWithSkuDto.getImg());
            orderItem.setGoodsSku(goodsInfoWithSkuDto.getAttrJson());

            BigDecimal bigDecimalQty = new BigDecimal(orderItem.getQty());
            orderItem.setAmount(bigDecimalQty.multiply(orderItem.getRetailPrice())); //总价计算
            //供货价
            //orderItem.setPrice(goodsInfoWithSkuDto.getWholeSalePrice());

            //采购商折扣 add by wanglq 20170927
            if (isB2b) {//按件计价商品需要
                logger.info("============采购商折扣=======================");
                orderItem.setRetailPrice(classifyDiscountService.getSkuPriceByUserGrade(addOrderDto.getUserID(), goodsInfoWithSkuDto.getSkuID())); //实际成交价
                orderItem.setAmount((bigDecimalQty.multiply(orderItem.getRetailPrice())).setScale(2, BigDecimal.ROUND_HALF_UP));//总金额
                //    }
            } else {
                //中银金行价格
                if (bocgold
                        && com.google.common.base.Objects.equal(addOrderDto.getDiscountWay(), 2)) {
                    logger.info("==============================中银金行价格==================================");
                    discountWay = 2;
                    QueryGoodsSkuRateDto queryGoodsSkuRateDto = (QueryGoodsSkuRateDto) goodsService.goodsSkuUserDiscountRate(goodsCart.getUserID(), goodsCart.getSkuID());
                    if (queryGoodsSkuRateDto != null && StringUtils.isNotEmpty(queryGoodsSkuRateDto.getDiscountRate())) {
                        BigDecimal priceRate = orderItem.getAmount().multiply(new BigDecimal(queryGoodsSkuRateDto.getDiscountRate()));
                        BigDecimal priceRate1 = (priceRate.divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));  //四舍五入、保留两位小数
                        orderItem.setAmount(priceRate1); //总价计算
                        BigDecimal discountRate = new BigDecimal(queryGoodsSkuRateDto.getDiscountRate()).multiply(new BigDecimal(100));
                        orderItem.setDiscountRate(discountRate.intValue());
                        // 下面订单扣点金额 是存的 sxp的二级  还是供货价格比例的扣点
                        orderItem.setRetailPrice(BigDecimalUtil.div(orderItem.getAmount(), BigDecimal.valueOf(orderItem.getQty())));
                    }
                } else if (com.google.common.base.Objects.equal(addOrderDto.getDiscountWay(), 3) && isOpenCom) {// 管理者购买直接抵扣
                    discountWay = 3;
                    logger.info("===========================================================================奖金折扣");
                    double newAmt = commissionUserService.getDueAmountForItem(addOrderDto.getUserID(), orderItem);
                    pointAmountForCom += BigDecimalUtil.sub(orderItem.getAmount(), BigDecimal.valueOf(newAmt)).doubleValue();//优惠
                    orderItem.setAmount(BigDecimalUtil.div(BigDecimal.valueOf(newAmt), BigDecimal.valueOf(1), 2));//折扣金额
                    orderItem.setRetailPrice(BigDecimalUtil.div(orderItem.getAmount(), BigDecimal.valueOf(orderItem.getQty())));//单价
                }
            }

            //获取部门和员工回扣值
            Map<String, Integer> map = goodsClassifyCommissionService.getRateByClazzID2(goodsInfoWithSkuDto.getClassifyID(),
                    goodsInfoWithSkuDto.getSubClassifyID(), orderItem.getGoodsID(), selID);

            Integer bankVal = MapUtils.getInteger(map, Constants.bankVal, 0);
            Integer employeeVal = MapUtils.getInteger(map, Constants.employeeVal, 0);
            BigDecimal commission1 = orderItem.getAmount().multiply(new BigDecimal(bankVal));
            BigDecimal commission = (commission1.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP));  //四舍五入、保留两位小数
            orderItem.setCommission(commission);
            BigDecimal commission2 = orderItem.getAmount().multiply(new BigDecimal(employeeVal));
            BigDecimal employeeCommission = (commission2.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP));  //四舍五入、保留两位小数
            orderItem.setEmployeeCommission(employeeCommission);


            orderItem.setMd5(CommonUtils.MD5(getAmountForMD5(orderItem.getAmount().toString()) + orderItem.getQty() + ProConstants.salt));  //价格加密字段
            //供货价
            if (orderItem.getPrice() != null) {
                if (goodsInfo.getPriceType() == 0) {
                    dueAmount = dueAmount.add(goodsInfoWithSkuDto.getWholeSalePrice().multiply(new BigDecimal(orderItem.getQty())));
                } else {//实时金价供货价
                    dueAmount = dueAmount.add(goodsService.getTodayGoldPrice(goodsInfo.getSupplierID(), goodsInfo.getAttr(), goodsInfoWithSkuDto.getAttrJson()));
                }
            }
            orderItemMapper.insertSelective(orderItem);
            //插入积分系统，用户与客户关系数据

            //插入订单明细快照表
            insertSnapshot(orderItem.getItemID(), goodsCart1.getCompanyID());

            //获取购物车ID用于删除
            cartIDList.add(goodsCart.getCartID());

            //下单减库存
            goodsService.changeInventory(1, orderItem.getGoodsID(), orderItem.getSkuID(), orderItem.getQty(), orderItem.getItemID());

            pointAmountForComMap.put(orderID, pointAmountForCom);

        }
        /* for end*/

        //抵扣金豆 added by tim peng 2017-4-6
        if (paraPoint != null && isOpenGoldPoint()) {
            DataResult result = HttpUtil.httpPost(ProConstants.setUseGolden, paraPoint, restTemplate);
            if (result.getIsSuccess() == 0) {
                throw new ServiceException("金豆服务抵扣失败,message=" + result.getErrorDesc(), RestConst.ErrorCode.SERVICE_FAIL);
            }
        }

        //删除购物车单据
        goodsCartMapper.deleteByPrimaryKey(cartIDList);

        //获取orderIDList用于添加索引
        List<Long> orderIDList = new ArrayList<>();

        //更新每个订单的总价和扣点金额以及商品数量
        BigDecimal allAmountTotal = new BigDecimal(0.00);
        for (Long orderID1 : param.values()) {
            orderIDList.add(orderID1);
            int qty = orderItemMapper.selectqtyByOrderID(orderID1);
            BigDecimal amountTotal = orderItemMapper.selectSumAmountByOrderID(orderID1);
            allAmountTotal = Arith.add(allAmountTotal, amountTotal);
            //金豆抵扣,因可能拆单，只计算一次
            if (pointAmount.compareTo(BigDecimal.ZERO) == 1) {
                amountTotal = amountTotal.subtract(pointAmount);
                if (amountTotal.compareTo(BigDecimal.ZERO) < 0) {
                    amountTotal = BigDecimal.ZERO;
                }
                pointAmount = BigDecimal.ZERO;
            }

            Map<String, Object> param1 = new HashMap<String, Object>();
            if (isB2b) {
                param1.put("couponType", "7");//采购商折扣
                param1.put("type", 2);
            }

            //BigDecimal commission11 = orderItemMapper.selectSumCommissionByOrderID(orderID1);
            Map<String, Double> commissionMap = orderItemMapper.selectTotalCommissionByOrderID(orderID1);
            amountTotal = BigDecimalUtil.div(amountTotal, BigDecimal.valueOf(1), 2);//折扣金额
            String md5 = CommonUtils.MD5(getAmountForMD5(amountTotal.toString()) + qty + ProConstants.salt);//md5加密

            param1.put("qty", qty);
            param1.put("orderID", orderID1);
            param1.put("amount", amountTotal);
            param1.put("dueAmount", dueAmount);
            param1.put("md5", md5);
            orderInfoMapper.updateAmountByPrimaryKey(param1);
        }

        //优惠券使用锁定 added by timpeng 2018-8-15
        if (couponID != null && discountAmount != null &&
                discountAmount.compareTo(BigDecimal.ZERO) == 1 && couponID > 0 && allAmountTotal.compareTo(BigDecimal.ZERO) == 1) {
            for (Long tmpOrderID : param.values()) {
                OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(tmpOrderID);
                if (null != orderInfo) {
                    //优惠券金额按比例划扣
                    orderInfo.setPointAmount(discountAmount.multiply(orderInfo.getAmount().divide(allAmountTotal, 2, BigDecimal.ROUND_HALF_UP)));
                    Map<String, Object> paraCoupon1 = new HashMap<>();
                    paraCoupon1.put("discount", orderInfo.getPointAmount());
                    paraCoupon1.put("orderNO", orderInfo.getOrderNO());
                    Map<String, Object> paraCoupon = new HashMap<>();
                    paraCoupon.put("getID", couponID);
                    paraCoupon.put("orderID", tmpOrderID);
                    paraCoupon.put("extJSON", JSONObject.fromObject(paraCoupon1).toString());
                    DataResult result = HttpUtil.httpPost(ProConstants.postUserCoupon, paraCoupon, restTemplate);
                    if (result.getIsSuccess() == 0) {
                        //throw new ServiceException("优惠券服务抵扣失败,message=" + result.getErrorDesc(), RestConst.ErrorCode.SERVICE_FAIL);
                        logger.error("优惠券服务抵扣失败,message=" + result.getErrorDesc());
                    }
                    //优惠券金额订单项目按比例划扣
                    List<OrderItem> tmpItemList = orderItemMapper.selectByOrderID(tmpOrderID);
                    for (OrderItem orderItem : tmpItemList) {
                        orderItem.setDiscountAmount(orderInfo.getPointAmount().multiply(orderItem.getAmount().divide(orderInfo.getAmount(), 2, BigDecimal.ROUND_HALF_UP)));
                        orderItemMapper.updateByPrimaryKeySelective(orderItem);
                    }
                    BigDecimal amountTmp = orderInfo.getAmount().subtract(orderInfo.getPointAmount());
                    Map<String, Object> param1 = new HashMap<String, Object>();
                    param1.put("pointAmount", orderInfo.getPointAmount());
                    param1.put("orderID", tmpOrderID);
                    param1.put("Amount", amountTmp);
                    param1.put("md5", CommonUtils.MD5(getAmountForMD5(amountTmp.toString()) + orderInfo.getqty() + ProConstants.salt));
                    orderInfoMapper.updateAmountByPrimaryKey(param1);

                    orderInfoMapper.updateAmountByPrimaryKey(param1);
                }
            }
        }
        // end 优惠券使用锁定

        if (goldPriceChangeFlag == false) {
            expireKey = new DefaultExpireKey();
            throw new ServiceException(allAmountTotal.toString(), "006");
        }
        orderIndexService.addIndex(orderIDList, mobile);  //添加索引

        return orderIDList;
    }


    //按userID查询该用户最新的发票抬头信息
    public Object getLatestInvoicesByUserID(Long userID) {
        String invoicesHead = orderInfoMapper.selectLatestInvoicesByUserID(userID);
        if (invoicesHead == null) {
            return "";
        }
        return invoicesHead;
    }

    //按userID查询该用户最新的发票抬头信息
    public Object getLatestInvoicesByUserIDV2(Long userID) {
        Map invoicesHead = orderInfoMapper.selectLatestInvoicesByUserIDV2(userID);
        if (invoicesHead == null) {
            return null;
        }
        return invoicesHead;
    }

    //复制下单/立即购买
    public Object copyOrDirectBuyOrder(CopyOrDirectBuyDto buyDto, boolean isb2b) {
        logger.info("==============================================" + buyDto.getDiscountWay());
        Long orderInfoID = null;
        String mobile = null;
        //金豆金额
        BigDecimal pointAmount = BigDecimal.ZERO;

        //供应商成本 add by pengzh 2018-3-26
        BigDecimal dueAmount = BigDecimal.ZERO;

        //优惠券总金额
        BigDecimal discountAmount = BigDecimal.ZERO;
        //优惠券领用ID
        Long couponID = 0l;

        double pointAmountForCom = 0d;
        String key = "copyOrDirectBuyOrder";
        boolean bocgold = getBocgold();
        boolean isOpenCom = commissionUserService.isClazzSupply(SystemContext.getCompanyID(), restTemplate)
                && commissionUserService.isAdmin(buyDto.getUserID()) && goodsService.isActiveAdmin(buyDto.getUserID());
        boolean goldPriceChangeFlag = true;
        if (buyDto.getType() == 1) {   //复制下单
            OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(buyDto.getOrderID());
            orderInfo.setCouponType("1");
            orderInfo.setPointAmount(BigDecimal.ZERO);
            key = key + buyDto.getOrderID();
            if (expireKey.exists(key)) {
                throw new ServiceException("您刚刚已经提交了，请勿重复操作");
            } else {
                expireKey.add(key);
            }
            if (orderInfo.getState() != 4 && orderInfo.getState() != 0) {
                throw new ServiceException("原订单尚未完成，不能重复下单", RestConst.ErrorCode.DATABASE_ERROR);
            }
            List<OrderItem> itemList = orderItemMapper.selectByOrderID(buyDto.getOrderID());
            orderInfo.setOrderID(IdGen.get().nextId());
            orderInfo.setOrderNO(CodeGenerator.INSTANCE.nextId());
            orderInfo.setState(1);
            orderInfo.setPayNo(null);
            //  添加线下支付 offline线下支付 add buyadong 2017-6-14 10:00:49
            if (buyDto.getOrderPayType() != null && buyDto.getOrderPayType() == 1) {
                //order3线下支付
                orderInfo.setOrderPayType(buyDto.getOrderPayType());
                // orderInfo.setPayTime(CommonUtils.getCurTimestamp());
                orderInfo.setCheckCode(getRandByNum(4));//核销码
                orderInfo.setPayNo(orderInfo.getOrderNO());// payno = orderno added by pengzh 17-8-9
                orderInfo.setCheckInvalidTime(DateUtils.addDays(new Date(), +7).getTime());//失效时间
            } else {
                orderInfo.setOrderPayType(null);
                orderInfo.setCheckCode(null);
                orderInfo.setCheckInvalidTime(null);
                orderInfo.setCheckUserID(null);
                orderInfo.setCheckUserName(null);
                orderInfo.setCancelTime(null);
                orderInfo.setCancelUserName(null);
                orderInfo.setCancelUserID(null);
                orderInfo.setCancelMemo(null);
            }
            orderInfo.setPayTime(null);
            orderInfo.setPointQty(BigDecimal.ZERO);
            orderInfo.setAddressID(buyDto.getAddressID().toString());  //更新订单中新增的地址信息

            orderInfo.setCompanyID(SystemContext.getCompanyID());
            //create by zll
            String url = ProConstants.getAddress + buyDto.getAddressID().toString();
            DataResult result = HttpUtil.httpGet(url, restTemplate);
            if (result.getIsSuccess() == 1) {
                Map<String, Object> mapResult = (Map<String, Object>) result.getData();
                if (mapResult != null) {

                    orderInfo.setReceiverAddress(mapResult.get("address").toString());
                    orderInfo.setReceiverName(mapResult.get("contacts").toString());
                    orderInfo.setReceiverPhone(mapResult.get("contactPhone").toString());

                    OrderAddress orderAddress = new OrderAddress();
                    orderAddress.setAddressId(IdGen.get().nextId());
                    orderAddress.setOrderId(orderInfo.getOrderID());
                    orderAddress.setProvince((int) mapResult.get("province"));
                    orderAddress.setCity((int) mapResult.get("city"));
                    orderAddress.setDistrict((int) mapResult.get("district"));
                    orderAddressMapper.insertSelective(orderAddress);
                }
            } else {
                orderInfo.setReceiverAddress("无信息");
                orderInfo.setReceiverName("无信息");
                orderInfo.setReceiverPhone("无信息");
            }

            orderInfo.setInvoices(buyDto.getInvoices());
            orderInfo.setInvoicesHead(buyDto.getInvoicesHead());
            orderInfo.setInvoicesNO(buyDto.getInvoicesNO());
            orderInfo.setAddTime(CommonUtils.getCurTimestamp());
            orderInfo.setSendTime(null);
            orderInfo.setFinishTime(null);
            orderInfo.setSureTime(null);

            //获取用户下单所需用户及其组织信息
            UserInfoForOrderDto userInfoForOrderDto = (UserInfoForOrderDto) getUserInfoForOrder(orderInfo.getUserID());
            mobile = userInfoForOrderDto.getMobile();
            orderInfo.setCompanyID(SystemContext.getCompanyID());
            orderInfo.setUserName(userInfoForOrderDto.getUserName());
            orderInfo.setSalesManagerID(userInfoForOrderDto.getSalesManagerID());
            orderInfo.setSalesID(userInfoForOrderDto.getSalesID());
            orderInfo.setStoreManagerID(getStoreManagerByUserID(buyDto.getUserID()));
            orderInfo.setShopID(buyDto.getShopID());

            orderInfo.setBranchID(userInfoForOrderDto.getBranchID());
            orderInfo.setTwoLevelBranchID(userInfoForOrderDto.getTwoLevelBranchID());
            orderInfo.setSubbranchID(userInfoForOrderDto.getSubbranchID());

            //小商城存在多个商城切换， 结构信息存购买商城层级 2018-4-8
            if (!isb2b) {
                Map<String, Object> mallInfo = getMallInfo(buyDto.getShopID());
                Integer distGrade = MapUtils.getInteger(mallInfo, "level");
                switch (distGrade.intValue()) {
                    case 2:
                        //一级代理
                        orderInfo.setBranchID(MapUtils.getLong(mallInfo, "oID"));
                        break;
                    case 3:
                        //二级代理
                        orderInfo.setBranchID(MapUtils.getLong(mallInfo, "branchID"));//分部
                        orderInfo.setTwoLevelBranchID(MapUtils.getLong(mallInfo, "oID"));//二级分部
                        break;
                    case 4:
                        //三级代理
                        orderInfo.setBranchID(MapUtils.getLong(mallInfo, "branchID"));//分部
                        orderInfo.setTwoLevelBranchID(MapUtils.getLong(mallInfo, "twoLevelBranchID"));//二级分部
                        orderInfo.setSubbranchID(MapUtils.getLong(mallInfo, "oID"));//支部
                        break;
                    case 1:
                        //0级
                        throw new ServiceException("当前商城资料有误，不支持");
                }
            }


            orderInfoMapper.insertSelective(orderInfo);

            orderInfoID = orderInfo.getOrderID();  //用于后续

            List<SkuPriceDto> goodsPrice = buyDto.getSkuPrice();
            Map<Long, BigDecimal> skuPriceMap = new HashMap();
            for (SkuPriceDto p : goodsPrice) {
                skuPriceMap.put(p.getSkuID(), p.getPrice());
            }
            for (OrderItem orderItem : itemList) {
                GoodsInfoWithSkuDto goodsInfoWithSkuDto = new GoodsInfoWithSkuDto();
                GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(orderItem.getGoodsID());
                //add by wanglq
                if (isb2b) {
                    goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuIDv2(orderItem.getSkuID(), 0l);
                } else {
                    goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuIDvShop(orderItem.getSkuID(), 0l, buyDto.getShopID());
                }

                // add by lmn 实时金价
                if (goodsInfo.getPriceType() == 1) {
                    BigDecimal pri = null;
                    if (isb2b) {
                        pri = goodsService.getTodayGoldPriceByOtherFee(goodsInfo.getSupplierID(), goodsInfo.getAttr(), goodsInfoWithSkuDto.getAttrJson(), goodsInfoWithSkuDto.getPrice());
                    } else {
                        GoodsSkuShop skuShop = goodsSkuShopMapper.selectBySkuIDAndShopID(orderItem.getSkuID(), buyDto.getShopID());
                        pri = goodsService.getTodayGoldPriceByOtherFee(goodsInfo.getSupplierID(), goodsInfo.getAttr(), goodsInfoWithSkuDto.getAttrJson(), skuShop.getOtherFee());
                    }
                    orderItem.setPrice(pri);
                    orderItem.setRetailPrice(pri);
                    //TODO 实时金价价格变动不提示
                    /*if (goldPriceChangeFlag) {
                        goldPriceChangeFlag = pri.compareTo(skuPriceMap.get(orderItem.getSkuID())) == 0 ? true : false;
                    }*/
                } else {
                    orderItem.setRetailPrice(goodsInfoWithSkuDto.getPrice());
                    //供应商供货价，成本价 added by pengzh 2018-3-26
                    orderItem.setPrice(goodsInfoWithSkuDto.getPrice());
                }

                Long VipPriceSW = getVipPriceSW(orderInfo.getCompanyID());//获取开关
                logger.info("buyDto.getDiscountType()==" + buyDto.getDiscountType());
                if (bocgold && buyDto.getDiscountType() != null && buyDto.getDiscountType() == 0) {
                    VipPriceSW = 1L;
                }

                if (2 == VipPriceSW && goodsInfo.getPriceType() == 0) {//会员价
                    goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuIDv2(orderItem.getSkuID(), userInfoForOrderDto.getVipLevel());
                    BigDecimal vipPrice = goodsInfoWithSkuDto.getVipPrice();
                    if (null != vipPrice) {
                        orderItem.setRetailPrice(vipPrice);
                        if (userInfoForOrderDto.getType() == 3 || userInfoForOrderDto.getType() == 4) {
                            buyDto.setDiscountWay(1);//会员
                        }
                    } else {
                        orderItem.setRetailPrice(goodsInfoWithSkuDto.getPrice());
                    }
                } /*else {//老版本兼容
                    goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuIDv2(orderItem.getSkuID(), 0l);
                    orderItem.setRetailPrice(goodsInfoWithSkuDto.getPrice());
                }*/
                goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuID(orderItem.getSkuID());
                if (!goodsInfoWithSkuDto.getState().equals("Shelve")) {
                    throw new ServiceException("商品已失效，不能购买", RestConst.ErrorCode.DATABASE_ERROR);
                }
                if (goodsInfoWithSkuDto.getInventory() < orderItem.getQty()) {
                    throw new ServiceException("库存不足！" + orderItem.getGoodsName(), RestConst.ErrorCode.DATABASE_ERROR);
                }

                orderItem.setItemID(IdGen.get().nextId());
                orderItem.setOrderID(orderInfo.getOrderID());
                orderItem.setGoodsSku(goodsInfoWithSkuDto.getAttrJson());
                BigDecimal bigDecimalQty = new BigDecimal(orderItem.getQty());
                orderItem.setAmount(bigDecimalQty.multiply(orderItem.getRetailPrice())); //总价计算

                if (isb2b) {//按件计价商品折扣
                    buyDto.setDiscountWay(4);

                    orderItem.setRetailPrice(classifyDiscountService.getSkuPriceByUserGrade(buyDto.getUserID(), goodsInfoWithSkuDto.getSkuID())); //实际成交价
                    orderItem.setAmount((bigDecimalQty.multiply(orderItem.getRetailPrice())).setScale(2, BigDecimal.ROUND_HALF_UP));//总金额
                    // }
                } else {
                    //中银金行价格
                    if (bocgold && com.google.common.base.Objects.equal(buyDto.getDiscountWay(), 2)) {
                        logger.info("==============================中银金行价格==================================");
                        QueryGoodsSkuRateDto queryGoodsSkuRateDto = (QueryGoodsSkuRateDto) goodsService.goodsSkuUserDiscountRate(orderInfo.getUserID(), orderItem.getSkuID());
                        if (queryGoodsSkuRateDto != null && StringUtils.isNotEmpty(queryGoodsSkuRateDto.getDiscountRate())) {
                            BigDecimal priceRate = orderItem.getAmount().multiply(new BigDecimal(queryGoodsSkuRateDto.getDiscountRate()));
                            BigDecimal priceRate1 = (priceRate.divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));  //四舍五入、保留两位小数
                            orderItem.setAmount(priceRate1); //总价计算
                            BigDecimal discountRate = new BigDecimal(queryGoodsSkuRateDto.getDiscountRate()).multiply(new BigDecimal(100));
                            orderItem.setDiscountRate(discountRate.intValue());
                            // 下面订单扣点金额 是存的 sxp的二级  还是供货价格比例的扣点
                            orderItem.setRetailPrice(BigDecimalUtil.div(orderItem.getAmount(), BigDecimal.valueOf(orderItem.getQty())));
                        }
                    } else if (com.google.common.base.Objects.equal(buyDto.getDiscountWay(), 3) && isOpenCom) {// 管理者购买直接抵扣
                        double newAmt = commissionUserService.getDueAmountForItem(buyDto.getUserID(), orderItem);
                        pointAmountForCom += BigDecimalUtil.sub(orderItem.getAmount(), BigDecimal.valueOf(newAmt)).doubleValue();//优惠
                        orderItem.setAmount(BigDecimal.valueOf(newAmt));//折扣金额
                        orderItem.setRetailPrice(BigDecimalUtil.div(orderItem.getAmount(), BigDecimal.valueOf(orderItem.getQty())));
                    }
                }

                //获取扣点值
                Map<String, Integer> map = goodsClassifyCommissionService.getRateByClazzID2(goodsInfoWithSkuDto.getClassifyID(),
                        goodsInfoWithSkuDto.getSubClassifyID(), orderItem.getGoodsID(), orderInfo.getSellerID());
                Integer bankVal = MapUtils.getInteger(map, Constants.bankVal, 0);
                Integer employeeVal = MapUtils.getInteger(map, Constants.employeeVal, 0);
                BigDecimal commission1 = orderItem.getAmount().multiply(new BigDecimal(bankVal));
                BigDecimal commission = (commission1.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP));  //四舍五入、保留两位小数
                orderItem.setCommission(commission);
                BigDecimal commission2 = orderItem.getAmount().multiply(new BigDecimal(employeeVal));
                BigDecimal employeeCommission = (commission2.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP));  //四舍五入、保留两位小数
                orderItem.setEmployeeCommission(employeeCommission);

                orderItem.setMd5(CommonUtils.MD5(getAmountForMD5(orderItem.getAmount().toString()) + orderItem.getQty() + ProConstants.salt));  //价格加密字段
                //供货价
                if (orderItem.getPrice() != null) {
                    if (goodsInfo.getPriceType() == 0) {
                        dueAmount = dueAmount.add(goodsInfoWithSkuDto.getWholeSalePrice().multiply(new BigDecimal(orderItem.getQty())));
                    } else {//实时金价供货价
                        dueAmount = dueAmount.add(goodsService.getTodayGoldPrice(goodsInfo.getSupplierID(), goodsInfo.getAttr(), goodsInfoWithSkuDto.getAttrJson()));
                    }
                }
                orderItemMapper.insertSelective(orderItem);

                //插入订单明细快照表
                insertSnapshot(orderItem.getItemID(), orderInfo.getCompanyID());

                //下单减库存
                goodsService.changeInventory(1, orderItem.getGoodsID(), orderItem.getSkuID(), orderItem.getQty(), orderItem.getItemID());
            }
        } else if (buyDto.getType() == 2) {  //立即购买
            if (buyDto.getQty() <= 0) {
                throw new ServiceException("商品数量必须大于0", RestConst.ErrorCode.FORM_FAIL);
            }
            if (buyDto.getInvoices() == 2) {
                if (buyDto.getInvoicesHead() == null) {
                    throw new ServiceException("请填写发票抬头", RestConst.ErrorCode.FORM_FAIL);
                }
            }
            key = key + buyDto.getAddressID() + buyDto.getUserID() + buyDto.getSkuID() + buyDto.getQty();
            if (expireKey.exists(key)) {
                throw new ServiceException("您刚刚已经提交了，请勿重复操作");
            } else {
                expireKey.add(key);
            }

            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setOrderID(IdGen.get().nextId());
            orderInfo.setOrderNO(CodeGenerator.INSTANCE.nextId());
            orderInfo.setInvoices(buyDto.getInvoices());
            orderInfo.setInvoicesHead(buyDto.getInvoicesHead());
            orderInfo.setInvoicesNO(buyDto.getInvoicesNO());
            orderInfo.setAddressID(buyDto.getAddressID().toString());
            orderInfo.setCompanyID(SystemContext.getCompanyID());

            if (orderInfo.getInvoices() != null && orderInfo.getInvoices() == 2) {
                if (StringUtils.isEmpty(orderInfo.getInvoicesHead())) {
                    throw new ServiceException("请填写发票抬头", RestConst.ErrorCode.FORM_FAIL);
                }
            }
            //create by zll
            String url = ProConstants.getAddress + buyDto.getAddressID().toString();
            DataResult result = HttpUtil.httpGet(url, restTemplate);

            if (result.getIsSuccess() == 1) {

                Map<String, Object> mapResult = (Map<String, Object>) result.getData();
                if (mapResult != null) {

                    orderInfo.setReceiverAddress(mapResult.get("address").toString());
                    orderInfo.setReceiverName(mapResult.get("contacts").toString());
                    orderInfo.setReceiverPhone(mapResult.get("contactPhone").toString());

                    OrderAddress orderAddress = new OrderAddress();
                    orderAddress.setAddressId(IdGen.get().nextId());
                    orderAddress.setOrderId(orderInfo.getOrderID());
                    orderAddress.setProvince((int) mapResult.get("province"));
                    orderAddress.setCity((int) mapResult.get("city"));
                    orderAddress.setDistrict((int) mapResult.get("district"));
                    orderAddressMapper.insertSelective(orderAddress);
                }
            } else {
                orderInfo.setReceiverAddress("无信息");
                orderInfo.setReceiverName("无信息");
                orderInfo.setReceiverPhone("无信息");
            }
            orderInfo.setAddTime(CommonUtils.getCurTimestamp());
            orderInfo.setUserID(buyDto.getUserID());
            orderInfo.setState(1);
            orderInfo.setSellerID(buyDto.getSellerID());
            orderInfo.setSellerName(buyDto.getSellerName());

            //获取用户下单所需用户及其组织信息
            UserInfoForOrderDto userInfoForOrderDto = (UserInfoForOrderDto) getUserInfoForOrder(buyDto.getUserID());
            mobile = userInfoForOrderDto.getMobile();
            orderInfo.setUserName(userInfoForOrderDto.getUserName());
            orderInfo.setSalesManagerID(userInfoForOrderDto.getSalesManagerID());
            orderInfo.setSalesID(userInfoForOrderDto.getSalesID());
            orderInfo.setBranchID(userInfoForOrderDto.getBranchID());
            orderInfo.setTwoLevelBranchID(userInfoForOrderDto.getTwoLevelBranchID());
            orderInfo.setSubbranchID(userInfoForOrderDto.getSubbranchID());


            //小商城存在多个商城切换， 结构信息存购买商城层级 2018-4-8
            if (!isb2b) {
                Map<String, Object> mallInfo = getMallInfo(buyDto.getShopID());
                Integer distGrade = MapUtils.getInteger(mallInfo, "level");
                switch (distGrade.intValue()) {
                    case 2:
                        //一级代理
                        orderInfo.setBranchID(MapUtils.getLong(mallInfo, "oID"));
                        break;
                    case 3:
                        //二级代理
                        orderInfo.setBranchID(MapUtils.getLong(mallInfo, "branchID"));//分部
                        orderInfo.setTwoLevelBranchID(MapUtils.getLong(mallInfo, "oID"));//二级分部
                        break;
                    case 4:
                        //三级代理
                        orderInfo.setBranchID(MapUtils.getLong(mallInfo, "branchID"));//分部
                        orderInfo.setTwoLevelBranchID(MapUtils.getLong(mallInfo, "twoLevelBranchID"));//二级分部
                        orderInfo.setSubbranchID(MapUtils.getLong(mallInfo, "oID"));//支部
                        break;
                    case 1:
                        //0级
                        throw new ServiceException("当前商城资料有误，不支持");
                }
            }


            //增加使用金豆,优惠策略 added by tim pengzh 2017-4-5, 保存金豆信息，但不抵扣
            orderInfo.setCouponType(buyDto.getCouponType());
            orderInfo.setPointQty(buyDto.getPointQty());
            orderInfo.setPointAmount(buyDto.getPointAmount());
            if (!isOpenGoldPoint()) {
                orderInfo.setPointQty(BigDecimal.ZERO);
                orderInfo.setPointAmount(BigDecimal.ZERO);
            }
            if (orderInfo.getPointQty() == null) {
                orderInfo.setPointQty(BigDecimal.ZERO);
            }
            if (orderInfo.getPointAmount() == null) {
                orderInfo.setPointAmount(BigDecimal.ZERO);
            }
            //金豆金额
            pointAmount = orderInfo.getPointAmount();
            if (pointAmount != null && pointAmount.compareTo(BigDecimal.ZERO) == 1 && "1".equals(buyDto.getCouponType()) && !isOpenPointDeduction()) {
                throw new ServiceException("您选择的金豆抵现活动已下线,请重新选择或更新版本", RestConst.ErrorCode.DATABASE_ERROR);
            }
            if (pointAmount.compareTo(BigDecimal.ZERO) == 1 && "1".equals(buyDto.getCouponType())) {
                Map<String, Object> paraPoint = new HashMap<String, Object>();
                paraPoint.put("amount", pointAmount);
                paraPoint.put("point", orderInfo.getPointQty());
                paraPoint.put("userID", orderInfo.getUserID());
                paraPoint.put("payNo", orderInfo.getOrderNO());
                result = HttpUtil.httpPost(ProConstants.setUseGolden, paraPoint, restTemplate);
                if (result.getIsSuccess() == 0) {
                    logger.error("金豆服务抵扣失败,message=" + result.getErrorDesc() + ",payno=" + orderInfo.getOrderNO());
                    //throw new ServiceException("金豆服务抵扣失败,message=" + result.getErrorDesc(), RestConst.ErrorCode.SERVICE_FAIL);
                }
            }

            //添加线下支付 线下支付 add buyadong 2017-6-14 10:00:49
            if (buyDto.getOrderPayType() != null && buyDto.getOrderPayType() == 1) {
                orderInfo.setOrderPayType(buyDto.getOrderPayType());
                orderInfo.setCheckCode(getRandByNum(4));//核销码
                orderInfo.setPayNo(orderInfo.getOrderNO());// payno = orderno added by pengzh 17-8-9
                orderInfo.setCheckInvalidTime(DateUtils.addDays(new Date(), +7).getTime());//失效时间
            }
            orderInfo.setCompanyID(SystemContext.getCompanyID());
            orderInfo.setShopID(buyDto.getShopID());
            orderInfo.setStoreManagerID(getStoreManagerByUserID(buyDto.getUserID()));

            //优惠类型: 1:金豆 2:优惠券,default:1
            if ("2".equals(buyDto.getCouponType()) && buyDto.getPointAmount().compareTo(BigDecimal.ZERO) == 1) {
                discountAmount = buyDto.getPointAmount();
                couponID = buyDto.getCouponID();
                if (couponID == null) {
                    logger.error("优惠券领用ID未指定");
                } else {
                    orderInfo.setPointAmount(buyDto.getPointAmount());
                }
            }
            orderInfoMapper.insertSelective(orderInfo);
            orderInfoID = orderInfo.getOrderID();  //用于后续


            Long VipPriceSW = getVipPriceSW(orderInfo.getCompanyID());//获取开关
            logger.info("com.google.common.base.Objects.equabuyDto.getDiscountType()==" + buyDto.getDiscountType());
            if (bocgold && com.google.common.base.Objects.equal(buyDto.getDiscountType(), 0)) {
                VipPriceSW = 1L;
            }
            GoodsInfoWithSkuDto goodsInfoWithSkuDto = new GoodsInfoWithSkuDto();
            OrderItem orderItem = new OrderItem();

            //add by wanglq
            if (isb2b) {
                goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuIDv2(buyDto.getSkuID(), 0l);
            } else {
                //TODO 为测试通过修改
                //goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuIDv2(buyDto.getSkuID(), 0l);
                goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuIDvShop(buyDto.getSkuID(), 0l, buyDto.getShopID());
            }

            GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(goodsInfoWithSkuDto.getGoodsID());

            // add by lmn
            if (goodsInfo.getPriceType() == 1) {
                BigDecimal pri = null;
                if (isb2b) {
                    pri = goodsService.getTodayGoldPriceByOtherFee(goodsInfo.getSupplierID(), goodsInfo.getAttr(), goodsInfoWithSkuDto.getAttrJson(), goodsInfoWithSkuDto.getPrice());
                } else {
                    GoodsSkuShop skuShop = goodsSkuShopMapper.selectBySkuIDAndShopID(buyDto.getSkuID(), buyDto.getShopID());
                    pri = goodsService.getTodayGoldPriceByOtherFee(goodsInfo.getSupplierID(), goodsInfo.getAttr(), goodsInfoWithSkuDto.getAttrJson(), skuShop.getOtherFee());
                }
                orderItem.setRetailPrice(pri);
                orderItem.setPrice(pri);
                //TODO 价格变动不提示
                //goldPriceChangeFlag = pri.compareTo(buyDto.getPrice()) == 0 ? true : false;
            } else {
                orderItem.setRetailPrice(goodsInfoWithSkuDto.getPrice());
                orderItem.setPrice(goodsInfoWithSkuDto.getPrice());
            }

            if (2 == VipPriceSW && goodsInfo.getPriceType() == 0) {//会员价
                goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuIDv2(buyDto.getSkuID(), userInfoForOrderDto.getVipLevel());
                BigDecimal vipPrice = goodsInfoWithSkuDto.getVipPrice();
                if (null != vipPrice) {
                    orderItem.setRetailPrice(vipPrice);
                    if (userInfoForOrderDto.getType() == 3 || userInfoForOrderDto.getType() == 4) {
                        buyDto.setDiscountWay(1);//会员
                    }
                } else {
                    orderItem.setRetailPrice(goodsInfoWithSkuDto.getPrice());
                }
            }
            goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuID(buyDto.getSkuID());
            if (!goodsInfoWithSkuDto.getState().equals("Shelve")) {
                throw new ServiceException("商品已失效，不能购买", RestConst.ErrorCode.DATABASE_ERROR);
            }
            if (goodsInfoWithSkuDto.getInventory() < buyDto.getQty()) {
                throw new ServiceException("库存不足！", RestConst.ErrorCode.DATABASE_ERROR);
            }
            //丝绸之路商品不参与抵扣 added by tim peng 2017-5-24
            if ("0".equalsIgnoreCase(goodsInfoWithSkuDto.getOffsetFlag()) && orderInfo.getPointQty() != null && orderInfo.getPointQty().compareTo(BigDecimal.ZERO) == 1) {
                throw new ServiceException("此商品不参与抵现", RestConst.ErrorCode.FORM_FAIL);
            }

            orderItem.setItemID(IdGen.get().nextId());
            orderItem.setOrderID(orderInfo.getOrderID());
            orderItem.setGoodsImg(goodsInfoWithSkuDto.getImg());
            orderItem.setGoodsName(goodsInfoWithSkuDto.getName());
            orderItem.setGoodsID(goodsInfoWithSkuDto.getGoodsID());
            orderItem.setQty(buyDto.getQty());
            orderItem.setSkuID(buyDto.getSkuID());
            orderItem.setGoodsSku(goodsInfoWithSkuDto.getAttrJson());
            BigDecimal bigDecimalQty = new BigDecimal(buyDto.getQty());
            orderItem.setAmount(bigDecimalQty.multiply(orderItem.getRetailPrice())); //总价计算


            //供应商供货价格
            if (isb2b) {
                //采购商折扣 add by wanglq 20170927
                buyDto.setDiscountWay(4);
                orderItem.setRetailPrice(classifyDiscountService.getSkuPriceByUserGrade(buyDto.getUserID(), goodsInfoWithSkuDto.getSkuID())); //实际成交价
                orderItem.setAmount((bigDecimalQty.multiply(orderItem.getRetailPrice())).setScale(2, BigDecimal.ROUND_HALF_UP));//总金额
                // }
            } else {
                //中银金行价格
                if (bocgold
                        && com.google.common.base.Objects.equal(buyDto.getDiscountWay(), 2)) {
                    logger.info("==============================中银金行价格==================================");
                    QueryGoodsSkuRateDto queryGoodsSkuRateDto = (QueryGoodsSkuRateDto) goodsService.goodsSkuUserDiscountRate(orderInfo.getUserID(), orderItem.getSkuID());
                    if (queryGoodsSkuRateDto != null && StringUtils.isNotEmpty(queryGoodsSkuRateDto.getDiscountRate())) {
                        BigDecimal priceRate = orderItem.getAmount().multiply(new BigDecimal(queryGoodsSkuRateDto.getDiscountRate()));
                        BigDecimal priceRate1 = (priceRate.divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));  //四舍五入、保留两位小数
                        orderItem.setAmount(priceRate1); //总价计算
                        BigDecimal discountRate = new BigDecimal(queryGoodsSkuRateDto.getDiscountRate()).multiply(new BigDecimal(100));
                        orderItem.setDiscountRate(discountRate.intValue());
                        // 下面订单扣点金额 是存的 sxp的二级  还是供货价格比例的扣点
                        orderItem.setRetailPrice(BigDecimalUtil.div(orderItem.getAmount(), BigDecimal.valueOf(orderItem.getQty())));
                    }
                } else if (com.google.common.base.Objects.equal(buyDto.getDiscountWay(), 3) && isOpenCom) {// 管理者购买直接抵扣
                    double newAmt = commissionUserService.getDueAmountForItem(buyDto.getUserID(), orderItem);
                    pointAmountForCom += BigDecimalUtil.sub(orderItem.getAmount(), BigDecimal.valueOf(newAmt)).doubleValue();//优惠
                    orderItem.setAmount(BigDecimalUtil.div(BigDecimal.valueOf(newAmt), BigDecimal.valueOf(1), 2));//折扣金额
                    orderItem.setRetailPrice(BigDecimalUtil.div(orderItem.getAmount(), BigDecimal.valueOf(orderItem.getQty())));
                }
            }

            //获取扣点值
            Map<String, Integer> map = goodsClassifyCommissionService.getRateByClazzID2(goodsInfoWithSkuDto.getClassifyID(),
                    goodsInfoWithSkuDto.getSubClassifyID(), orderItem.getGoodsID(), orderInfo.getSellerID());
            Integer bankVal = MapUtils.getInteger(map, Constants.bankVal, 0);
            Integer employeeVal = MapUtils.getInteger(map, Constants.employeeVal, 0);
            BigDecimal commission1 = orderItem.getAmount().multiply(new BigDecimal(bankVal));
            BigDecimal commission = (commission1.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP));  //四舍五入、保留两位小数
            orderItem.setCommission(commission);
            BigDecimal commission2 = orderItem.getAmount().multiply(new BigDecimal(employeeVal));
            BigDecimal employeeCommission = (commission2.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP));  //四舍五入、保留两位小数
            orderItem.setEmployeeCommission(employeeCommission);

            orderItem.setMd5(CommonUtils.MD5(getAmountForMD5(orderItem.getAmount().toString()) + orderItem.getQty() + ProConstants.salt));  //价格加密字段

            // 供应商成本
            if (orderItem.getPrice() != null) {
                if (goodsInfo.getPriceType() == 0) {
                    dueAmount = dueAmount.add(goodsInfoWithSkuDto.getWholeSalePrice().multiply(new BigDecimal(orderItem.getQty())));
                } else {//实时金价供货价
                    dueAmount = dueAmount.add(goodsService.getTodayGoldPrice(goodsInfo.getSupplierID(), goodsInfo.getAttr(), goodsInfoWithSkuDto.getAttrJson()));
                }
            }

            //优惠券抵扣
            if ("2".equals(buyDto.getCouponType()) && buyDto.getPointAmount().compareTo(BigDecimal.ZERO) == 1) {
                orderItem.setDiscountAmount(buyDto.getPointAmount());
                //orderItem.setAmount(orderItem.getAmount().subtract(buyDto.getPointAmount()));

                Map<String, Object> paraCoupon1 = new HashMap<>();
                paraCoupon1.put("discount", orderInfo.getPointAmount());
                paraCoupon1.put("orderNO", orderInfo.getOrderNO());
                Map<String, Object> paraCoupon = new HashMap<>();
                paraCoupon.put("getID", couponID);
                paraCoupon.put("orderID", orderInfo.getOrderID());
                paraCoupon.put("extJSON", JSONObject.fromObject(paraCoupon1).toString());
                DataResult result1 = HttpUtil.httpPost(ProConstants.postUserCoupon, paraCoupon, restTemplate);
                if (result1.getIsSuccess() == 0) {
                    logger.error("优惠券服务抵扣失败,message=" + result.getErrorDesc());
                    //throw new ServiceException("优惠券服务抵扣失败,message=" + result.getErrorDesc(), RestConst.ErrorCode.SERVICE_FAIL);
                }
            }

            orderItemMapper.insertSelective(orderItem);

            //插入订单明细快照表
            insertSnapshot(orderItem.getItemID(), orderInfo.getCompanyID());

            //下单减库存
            goodsService.changeInventory(1, orderItem.getGoodsID(), orderItem.getSkuID(), orderItem.getQty(), orderItem.getItemID());
        } else {
            throw new ServiceException("type参数传入错误", RestConst.ErrorCode.FORM_FAIL);
        }

        int qty = orderItemMapper.selectqtyByOrderID(orderInfoID);
        //金豆抵扣：原价 -金豆金额
        BigDecimal amountTotal = orderItemMapper.selectSumAmountByOrderID(orderInfoID).subtract(pointAmount);
        if (amountTotal.compareTo(BigDecimal.ZERO) < 0) {
            //不能为负数
            amountTotal = BigDecimal.ZERO;
        }

        //部门和员工回扣
        Map<String, Object> param1 = new HashMap<String, Object>();

        if (isb2b) {
            param1.put("couponType", "7");
            param1.put("type", 2);
        }
        amountTotal = BigDecimalUtil.div(amountTotal, BigDecimal.valueOf(1), 2);//折扣金额
        //实际支付
        if ("2".equals(buyDto.getCouponType()) && buyDto.getPointAmount().compareTo(BigDecimal.ZERO) == 1) {
            amountTotal = amountTotal.subtract(buyDto.getPointAmount());
        }
        String md5 = CommonUtils.MD5(getAmountForMD5(amountTotal.toString()) + qty + ProConstants.salt);//md5加密

        param1.put("orderID", orderInfoID);
        param1.put("qty", qty);
        param1.put("amount", amountTotal);
        param1.put("dueAmount", dueAmount);
        param1.put("md5", md5);
        orderInfoMapper.updateAmountByPrimaryKey(param1);


        List<Long> orderIDNewList = new ArrayList<>();
        orderIDNewList.add(orderInfoID);

        if (goldPriceChangeFlag == false) {
            expireKey = new DefaultExpireKey();
            /*"您购买的商品含有实时金价商品，价格已发生变动,变动后价格为"++"元。您是否继续支付?"*/
            throw new ServiceException(amountTotal.toString(), "006");
        } else {
            orderIndexService.addIndex(orderIDNewList, mobile);  //添加索引
        }
        return orderIDNewList;
    }

    private Long getStoreManagerByUserID(Long userID) {
        DataResult result = HttpUtil.httpGet(ProConstants.getStoreManagerByUserID + userID, restTemplate);
        if (!Objects.equal(result.getIsSuccess(), 1)) {
            throw new ServiceException("未获取到店长信息,调用base服务失败");
        }
        Long storeManager = Long.valueOf(result.getData() + "");
        return storeManager;
    }

    //复制下单获取商品最新信息快照
    public Object copyOrderGoodsInfo(Long orderID) throws Exception {
        List<GoodsInfoWithSkuMoreVo> infoWithSkuDtoList = new ArrayList<>();
        List<OrderItem> itemList = orderItemMapper.selectByOrderID(orderID);
        for (OrderItem item : itemList) {
            GoodsInfoWithSkuDto infoWithSkuDto = goodsInfoMapper.selectBySkuID(item.getSkuID());
            GoodsInfoWithSkuMoreVo goodsInfoWithSkuMoreVo = new GoodsInfoWithSkuMoreVo();
            BeanUtils.copyProperties(goodsInfoWithSkuMoreVo, infoWithSkuDto);
            goodsInfoWithSkuMoreVo.setQty(item.getQty());
            GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(item.getGoodsID());
            // add by lmn
            if (goodsInfo.getPriceType() == 1) {
                BigDecimal pri = goodsService.getTodayGoldPrice(goodsInfo.getSupplierID(), goodsInfo.getAttr(), goodsInfoWithSkuMoreVo.getAttrJson());
                goodsInfoWithSkuMoreVo.setPrice(pri);
            }
            //goodsInfoWithSkuMoreVo.setState("Shelve");//支付前已有orderValid验证
            goodsInfoWithSkuMoreVo.setInventory(goodsInfoWithSkuMoreVo.getInventory() + goodsInfoWithSkuMoreVo.getQty());//去除库存验证
            infoWithSkuDtoList.add(goodsInfoWithSkuMoreVo);
        }
        return infoWithSkuDtoList;
    }

    public Object calculationOrder(Long orderInfoID, int confirm, boolean isB2b) {
        /*String key = "copyOrDirectBuyOrder";*/
        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderInfoID);
        Integer type = getUserType(orderInfo.getUserID());
        if (Objects.equal(type, 6)) {
            isB2b = true;
        } else {
            isB2b = false;
        }
        List<OrderItem> itemList = orderItemMapper.selectByOrderID(orderInfo.getOrderID());
        boolean goldPriceChangeFlag = true;
        boolean bocgold = getBocgold();
        boolean isOpenCom = commissionUserService.isClazzSupply(SystemContext.getCompanyID(), restTemplate)
                && commissionUserService.isAdmin(orderInfo.getUserID()) && goodsService.isActiveAdmin(orderInfo.getUserID());
        double pointAmountForCom = 0d;
        for (OrderItem orderItem : itemList) {
            GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(orderItem.getGoodsID());
            //add by wanglq
            GoodsInfoWithSkuDto goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuIDv2(orderItem.getSkuID(), 0l);
            // add by lmn
            if (goodsInfo.getPriceType() == 1) {
                BigDecimal pri = goodsService.getTodayGoldPrice(goodsInfo.getSupplierID(), goodsInfo.getAttr(), goodsInfoWithSkuDto.getAttrJson());
                if (goldPriceChangeFlag) {
                    goldPriceChangeFlag = pri.compareTo(orderItem.getPrice()) == 0 ? true : false;
                }
                orderItem.setPrice(pri);
                orderItem.setRetailPrice(pri);
            } else {
                orderItem.setRetailPrice(goodsInfoWithSkuDto.getPrice());
                orderItem.setPrice(goodsInfoWithSkuDto.getPrice());
            }
        }
        if (goldPriceChangeFlag == true && com.google.common.base.Objects.equal(confirm, 0)) {
            return orderInfo.getOrderID();
        }
        orderInfo.setCouponType("1");
        orderInfo.setPointAmount(null);
       /* key = key + buyDto.getOrderID();
        if (expireKey.exists(key)) {
            throw new ServiceException("您刚刚已经提交了，请勿重复操作");
        } else {
            expireKey.add(key);
        }
        if (orderInfo.getState() != 4 && orderInfo.getState() != 0) {
            throw new ServiceException("原订单尚未完成，不能重复下单", RestConst.ErrorCode.DATABASE_ERROR);
        }*/

        /*orderInfo.setOrderID(IdGen.get().nextId());
        orderInfo.setOrderNO(CodeGenerator.INSTANCE.nextId());
        orderInfo.setState(1);*/
        /*orderInfo.setPayNo(null);*/
        //  添加线下支付 offline线下支付 add buyadong 2017-6-14 10:00:49
        /*if (orderInfo.getOrderPayType() != null && orderInfo.getOrderPayType() == 1) {
            //order3线下支付
            orderInfo.setOrderPayType(orderInfo.getOrderPayType());
            // orderInfo.setPayTime(CommonUtils.getCurTimestamp());
            orderInfo.setCheckCode(getRandByNum(4));//核销码
            orderInfo.setPayNo(orderInfo.getOrderNO());// payno = orderno added by pengzh 17-8-9
            orderInfo.setCheckInvalidTime(DateUtils.addDays(new Date(), +7).getTime());//失效时间
        } else {
            orderInfo.setOrderPayType(null);
            orderInfo.setCheckCode(null);
            orderInfo.setCheckInvalidTime(null);
            orderInfo.setCheckUserID(null);
            orderInfo.setCheckUserName(null);
            orderInfo.setCancelTime(null);
            orderInfo.setCancelUserName(null);
            orderInfo.setCancelUserID(null);
            orderInfo.setCancelMemo(null);
        }*/

        orderInfo.setPayTime(null);
        orderInfo.setPointQty(BigDecimal.ZERO);
        //orderInfo.setAddressID(buyDto.getAddressID().toString());  //更新订单中新增的地址信息

        //orderInfo.setCompanyID(SystemContext.getCompanyID());
        //create by zll
        /*String url = ProConstants.getAddress + buyDto.getAddressID().toString();
        DataResult result = HttpUtil.httpGet(url, restTemplate);
        if (result.getIsSuccess() == 1) {
            Map<String, Object> mapResult = (Map<String, Object>) result.getData();
            if (mapResult != null) {

                orderInfo.setReceiverAddress(mapResult.get("address").toString());
                orderInfo.setReceiverName(mapResult.get("contacts").toString());
                orderInfo.setReceiverPhone(mapResult.get("contactPhone").toString());

                OrderAddress orderAddress = new OrderAddress();
                orderAddress.setAddressId(IdGen.get().nextId());
                orderAddress.setOrderId(orderInfo.getOrderID());
                orderAddress.setProvince((int) mapResult.get("province"));
                orderAddress.setCity((int) mapResult.get("city"));
                orderAddress.setDistrict((int) mapResult.get("district"));
                orderAddressMapper.insertSelective(orderAddress);
            }
        } else {
            orderInfo.setReceiverAddress("无信息");
            orderInfo.setReceiverName("无信息");
            orderInfo.setReceiverPhone("无信息");
        }*/


        /*orderInfo.setInvoices(buyDto.getInvoices());
        orderInfo.setInvoicesHead(buyDto.getInvoicesHead());
        orderInfo.setInvoicesNO(buyDto.getInvoicesNO());
        orderInfo.setAddTime(CommonUtils.getCurTimestamp());
        //orderInfo.setPayTime(null);
        orderInfo.setSendTime(null);
        orderInfo.setFinishTime(null);
        orderInfo.setSureTime(null);*/

        //获取用户下单所需用户及其组织信息
        UserInfoForOrderDto userInfoForOrderDto = (UserInfoForOrderDto) getUserInfoForOrder(orderInfo.getUserID());
        /*mobile = userInfoForOrderDto.getMobile();
        orderInfo.setUserName(userInfoForOrderDto.getUserName());
        orderInfo.setSalesManagerID(userInfoForOrderDto.getSalesManagerID());
        orderInfo.setSalesID(userInfoForOrderDto.getSalesID());
        orderInfo.setBranchID(userInfoForOrderDto.getBranchID());
        orderInfo.setTwoLevelBranchID(userInfoForOrderDto.getTwoLevelBranchID());
        orderInfo.setSubbranchID(userInfoForOrderDto.getSubbranchID());*/

            /*if (null == buyDto.getCompanyID()) {//新老版本控制
                orderInfo.setCompanyID(ProConstants.COMPANY_ID);
            } else {
                orderInfo.setCompanyID(buyDto.getCompanyID());
            }*/
        //orderInfo.setCompanyID(SystemContext.getCompanyID());
        //orderInfoMapper.insertSelective(orderInfo);

        //orderInfoID = orderInfo.getOrderID();  //用于后续

        for (OrderItem orderItem : itemList) {
            //add by wanglq
            GoodsInfoWithSkuDto goodsInfoWithSkuDto = new GoodsInfoWithSkuDto();
            GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(orderInfo.getOrderID());

            goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuIDv2(orderInfo.getOrderID(), 0l);

            Long VipPriceSW = getVipPriceSW(orderInfo.getCompanyID());//获取开关
            logger.info("buyDto.getDiscountType()==" + orderInfo.getCouponType());
            if (bocgold && orderInfo.getCouponType() != null && orderInfo.getCouponType().equals("0")) {
                VipPriceSW = 1L;
            }

            if (2 == VipPriceSW && goodsInfo.getPriceType() == 0) {//会员价
                goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuIDv2(orderItem.getSkuID(), userInfoForOrderDto.getVipLevel());
                BigDecimal vipPrice = goodsInfoWithSkuDto.getVipPrice();
                if (null != vipPrice) {
                    orderItem.setRetailPrice(vipPrice);
                } else {
                    orderItem.setRetailPrice(goodsInfoWithSkuDto.getPrice());
                }
            } /*else {//老版本兼容
                    goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuIDv2(orderItem.getSkuID(), 0l);
                    orderItem.setRetailPrice(goodsInfoWithSkuDto.getPrice());
                }*/
            goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuID(orderItem.getSkuID());
            /*if (!goodsInfoWithSkuDto.getState().equals("Shelve")) {
                throw new ServiceException("商品已失效，不能购买", RestConst.ErrorCode.DATABASE_ERROR);
            }
            if (goodsInfoWithSkuDto.getInventory() < orderItem.getQty()) {
                throw new ServiceException("库存不足！" + orderItem.getGoodsName(), RestConst.ErrorCode.DATABASE_ERROR);
            }*/

            /*orderItem.setItemID(IdGen.get().nextId());*/
            /*orderItem.setOrderID(orderInfo.getOrderID());*/
            /*orderItem.setGoodsSku(goodsInfoWithSkuDto.getAttrJson());*/
            BigDecimal bigDecimalQty = new BigDecimal(orderItem.getQty());
            orderItem.setAmount(bigDecimalQty.multiply(orderItem.getRetailPrice())); //总价计算

            if (isB2b) {
                //采购商折扣 add by wanglq 20170927
                BigDecimal rate = classifyDiscountService.getDiscountRate(goodsInfoWithSkuDto.getSubClassifyID(), orderItem.getGoodsID(), orderInfo.getUserID());
                if (rate.intValue() != -1) {
                    isB2b = true;//采购商折扣
                    BigDecimal newAmt = BigDecimalUtil.mul(orderItem.getAmount(), rate);
                    orderItem.setAmount(BigDecimalUtil.div(newAmt, BigDecimal.valueOf(1), 2));//折扣金额
                    orderItem.setRetailPrice(BigDecimalUtil.div(orderItem.getAmount(), BigDecimal.valueOf(orderItem.getQty())));//单价
                }
            } else {
                //中银金行价格
                if (bocgold && com.google.common.base.Objects.equal(orderInfo.getCouponType(), 5)) {
                    logger.info("==============================中银金行价格==================================");
                    QueryGoodsSkuRateDto queryGoodsSkuRateDto = (QueryGoodsSkuRateDto) goodsService.goodsSkuUserDiscountRate(orderInfo.getUserID(), orderItem.getSkuID());
                    if (queryGoodsSkuRateDto != null && StringUtils.isNotEmpty(queryGoodsSkuRateDto.getDiscountRate())) {
                        BigDecimal priceRate = orderItem.getAmount().multiply(new BigDecimal(queryGoodsSkuRateDto.getDiscountRate()));
                        BigDecimal priceRate1 = (priceRate.divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));  //四舍五入、保留两位小数
                        orderItem.setAmount(priceRate1); //总价计算
                        BigDecimal discountRate = new BigDecimal(queryGoodsSkuRateDto.getDiscountRate()).multiply(new BigDecimal(100));
                        orderItem.setDiscountRate(discountRate.intValue());
                        // 下面订单扣点金额 是存的 sxp的二级  还是供货价格比例的扣点
                    }
                } else if (com.google.common.base.Objects.equal(orderInfo.getCouponType(), 4) && isOpenCom) {// 管理者购买直接抵扣
                    double newAmt = commissionUserService.getDueAmountForItem(orderInfo.getUserID(), orderItem);
                    pointAmountForCom += BigDecimalUtil.sub(orderItem.getAmount(), BigDecimal.valueOf(newAmt)).doubleValue();//优惠
                    orderItem.setAmount(BigDecimal.valueOf(newAmt));//折扣金额
                }
            }


            //获取扣点值
            /*int rate = goodsClassifyCommissionService.getRateByClazzID(goodsInfoWithSkuDto.getClassifyID(), goodsInfoWithSkuDto.getSubClassifyID());
            BigDecimal commission1 = orderItem.getAmount().multiply(new BigDecimal(rate));
            BigDecimal commission = (commission1.divide(new BigDecimal(1000), 4, BigDecimal.ROUND_HALF_UP));  //四舍五入、保留四位小数
            orderItem.setCommission(commission);*/
            Map<String, Integer> map = goodsClassifyCommissionService.getRateByClazzID2(goodsInfoWithSkuDto.getClassifyID(),
                    goodsInfoWithSkuDto.getSubClassifyID(), orderItem.getGoodsID(), orderInfo.getSellerID());
            Integer bankVal = MapUtils.getInteger(map, Constants.bankVal, 0);
            Integer employeeVal = MapUtils.getInteger(map, Constants.employeeVal, 0);
            BigDecimal commission1 = orderItem.getAmount().multiply(new BigDecimal(bankVal));
            BigDecimal commission = (commission1.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP));  //四舍五入、保留两位小数
            orderItem.setCommission(commission);
            BigDecimal commission2 = orderItem.getAmount().multiply(new BigDecimal(employeeVal));
            BigDecimal employeeCommission = (commission2.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP));  //四舍五入、保留两位小数
            orderItem.setEmployeeCommission(employeeCommission);

            orderItem.setMd5(CommonUtils.MD5(getAmountForMD5(orderItem.getAmount().toString()) + orderItem.getQty() + ProConstants.salt));  //价格加密字段
            if (goldPriceChangeFlag == false) {
                orderItemMapper.updateByPrimaryKey(orderItem);
            }

            //修改订单明细快照表
            updateSnapshot(orderItem.getItemID(), orderInfo.getCompanyID());

            //下单减库存
            //goodsService.changeInventory(1, orderItem.getGoodsID(), orderItem.getSkuID(), orderItem.getQty(), orderItem.getItemID());
        }

        int qty = orderItemMapper.selectqtyByOrderID(orderInfoID);
        //金豆抵扣：原价 -金豆金额
        BigDecimal amountTotal = orderItemMapper.selectSumAmountByOrderID(orderInfoID);
        if (amountTotal.compareTo(BigDecimal.ZERO) < 0) {
            //不能为负数
            amountTotal = BigDecimal.ZERO;
        }
        //BigDecimal commission11 = orderItemMapper.selectSumCommissionByOrderID(orderInfoID);
        Map<String, Double> commissionMap = orderItemMapper.selectTotalCommissionByOrderID(orderInfoID);

        Map<String, Object> param1 = new HashMap<String, Object>();

        //优惠金额
        BigDecimal pointAmountTotal = orderItemMapper.selectSumPointAmountByOrderID(orderInfoID);
        // add by wanglq 新增奖金优惠
        if (pointAmountTotal != null && pointAmountTotal.doubleValue() > 0) {
            //pointAmount = BigDecimalUtil.add(pointAmount, BigDecimal.valueOf(pointAmountForCom));
            //pointAmount = BigDecimalUtil.add(pointAmount, pointAmountTotal);
            amountTotal = BigDecimalUtil.sub(amountTotal, BigDecimal.valueOf(0));
            param1.put("pointAmount", pointAmountTotal);

            /*if (com.google.common.base.Objects.equal(orderInfo.getCouponType(), 2)) {
                param1.put("couponType", "5");
            } else if (com.google.common.base.Objects.equal(orderInfo.getCouponType(), 3)) {
                param1.put("couponType", "4");
            } else {
                param1.put("couponType", "1");
            }*/
        }
        if (isB2b) {
            param1.put("type", 2);
        }
        amountTotal = BigDecimalUtil.div(amountTotal, BigDecimal.valueOf(1), 2);//折扣金额
        String md5 = CommonUtils.MD5(getAmountForMD5(amountTotal.toString()) + qty + ProConstants.salt);//md5加密

        param1.put("orderID", orderInfoID);
        param1.put("qty", qty);
        param1.put("amount", amountTotal);
        //param1.put("commission", commission11);
        param1.put("commission", BigDecimal.valueOf(MapUtils.getDouble(commissionMap, "totalCommission", 0d)));
        param1.put("employeeCommission", BigDecimal.valueOf(MapUtils.getDouble(commissionMap, "totalEmployeeCommission", 0d)));
        param1.put("md5", md5);
        if (Objects.equal(confirm, 1)) {
            orderInfoMapper.updateAmountByPrimaryKey(param1);
            List<Long> list = new ArrayList();
            list.add(orderInfoID);
            orderIndexService.updateIndexTest(list);
        }

        if (goldPriceChangeFlag == false && com.google.common.base.Objects.equal(confirm, 0)) {
            /*"您购买的商品含有实时金价商品，价格已发生变动,变动后价格为"++"元。您是否继续支付?"*/
            throw new ServiceException(amountTotal.toString(), "006");
        }
        return orderInfo.getOrderID();
    }


    /**
     * @param payNO *
     * @return
     * @throws Exception
     */
    public Object selectByOrderPayNO(String payNO) throws Exception {
        List<OrderInfo> infoList = orderInfoMapper.selectByPayNo(payNO);
        List<OrderItem> itemList = orderItemMapper.selectByOrderPayNO(payNO);
        Map map = new HashMap();
        map.put("order", infoList);
        map.put("item", itemList);
        return map;
    }


    public Object selectByOrderIDS(OrderIDDto orderIDDto) throws Exception {
        List<Object> list = new ArrayList<>();
        for (Long orderID : orderIDDto.getOrderIDS()) {
            list.add(selectByOrderID(orderID, 1l, orderIDDto.getType()));
        }
        return list;
    }

    /**
     * @param orderID
     * @param type    1查询订单详细信息，2只查询订单信息
     * @return
     * @throws Exception
     */
    public Object selectByOrderID(Long orderID, Long userID, int type) throws Exception {
        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderID);
        //calculationOrder(orderInfo.getOrderID(),0);
        OrderLogistics orderLogistics = new OrderLogistics();
        Map<String, Object> traceabilityObject = new HashMap<>();
        Map<String, String> receiverMap = new HashMap<>();
        switch (type) {
            case 1:
                orderLogistics = selectLogisticByOrderID(orderID);
                receiverMap = getAddressInfo(orderInfo);
//                         receiverMap = getAddress(orderInfo.getAddressID());
                break;
            case 2:
                if (orderInfo.getUserID().equals(userID)) {
                    orderLogistics = selectLogisticByOrderID(orderID);
                    receiverMap = getAddressInfo(orderInfo);
                    //receiverMap = getAddress(orderInfo.getAddressID());
                } else {
                    orderInfo.setInvoices(null);
                    orderInfo.setInvoicesHead(null);
                    orderInfo.setInvoicesNO(null);
                }
                break;
        }
        Long deptID = 0L;
        if (!Objects.equal(orderInfo.getSubbranchID(), 0L)) {
            deptID = orderInfo.getSubbranchID();
        } else if (!Objects.equal(orderInfo.getTwoLevelBranchID(), 0L)) {
            deptID = orderInfo.getTwoLevelBranchID();
        } else if (!Objects.equal(orderInfo.getBranchID(), 0L)) {
            deptID = orderInfo.getBranchID();
        }
        String exSql = orderInfo.getUserID() + "/" + (orderInfo.getSalesManagerID() == null ? 0L : orderInfo.getSalesManagerID()) + "/" + deptID;
        DataResult result = HttpUtil.httpGet(ProConstants.getTraceability + exSql, restTemplate);
        if (result.getIsSuccess() == 1) {
            traceabilityObject = (Map<String, Object>) result.getData();
        } else {
            System.out.print("-----调用base服务查询用户溯源信息失败-----");
        }

        OrderDto orderDto = new OrderDto();
        orderDto.setOrderInfo(orderInfo);
        orderDto.setTraceabilityObject(traceabilityObject);
        orderDto.setOrderLogistics(orderLogistics);
        orderDto.setReceiver(receiverMap);
        List<OrderItemMoreDto> moreDtoList = new ArrayList<>();
        List<OrderItem> itemList = orderItemMapper.selectByOrderID(orderID);
        for (OrderItem item : itemList) {
            OrderItemMoreDto moreDto = new OrderItemMoreDto();
            BeanUtils.copyProperties(moreDto, item);
            GoodsSku goodsSku = goodsSkuMapper.selectByPrimaryKey(item.getSkuID());
            if (goodsSku == null) {
                moreDto.setInventory(0);
            } else {
                moreDto.setInventory(goodsSku.getInventory());
            }
            /*GoodsInfoWithSkuDto goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuID(item.getSkuID());
            if (goodsInfoWithSkuDto == null) {
                throw new ServiceException("未查到商品SKU信息", RestConst.ErrorCode.DATABASE_ERROR);
            }
            moreDto.setOffsetFlag(goodsInfoWithSkuDto.getOffsetFlag());*/
            //汾酒有删除sku的动作，sku可能不存在。故作修改
            GoodsInfo goods = goodsInfoMapper.selectByPrimaryKey(item.getGoodsID());
            moreDto.setOffsetFlag(goods.getOffsetFlag());
            moreDto.setPrdNo(goods.getPrdNo());
            moreDtoList.add(moreDto);
        }

        orderDto.setItemList(moreDtoList);
        return orderDto;
    }


    public Object selectCompanyIDByOrderID(Long orderID) throws Exception {
        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderID);
        if (orderInfo == null) {
            throw new ServiceException("未获取到订单信息");
        }
        return new DataResult(orderInfo.getCompanyID());
    }


    /**
     * 使用金豆抵扣,零支付单处理
     *
     * @param orderIDList
     * @param payType     1微信支付 2建行支付 3支付宝 4JS微信支付 5
     * @return
     */
    public Object zeroPay(List<Long> orderIDList, Integer payType) {
        if (!isOpenGoldPoint() || !isOpenPointDeduction())
            throw new ServiceException("您选择的金豆抵现活动已下线,请重新选择或更新版本", RestConst.ErrorCode.DATABASE_ERROR);

        logger.info("begin zeroPay...........");
        String payNo = CodeGenerator.INSTANCE.nextId();
        Long paytime = CommonUtils.getCurTimestamp();
        Map<String, Object> para = new HashMap<String, Object>();
        BigDecimal offsetQty = BigDecimal.ZERO;

        for (Long orderID : orderIDList) {
            List<OrderItem> itemList = orderItemMapper.selectByOrderID(orderID);

            for (OrderItem orderItem : itemList) {
                GoodsInfoWithSkuDto goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuID(orderItem.getSkuID());
                if (goodsInfoWithSkuDto == null) {
                    throw new ServiceException("未查到SKU信息", RestConst.ErrorCode.DATABASE_ERROR);
                }
                if (!goodsInfoWithSkuDto.getState().equals("Shelve")) {
                    OrderStateDto stateDto = new OrderStateDto();
                    stateDto.setOrderID(orderID);
                    stateDto.setState(0);
                    updateState(stateDto);
                    throw new ServiceException("商品已失效，不能购买", RestConst.ErrorCode.DATABASE_ERROR);
                }
            }
            Map<String, Object> param = new HashMap<>();
            param.put("orderID", orderID);
            param.put("payNo", payNo);
            param.put("payType", payType);
            orderInfoMapper.updatePayNoByPrimaryKey(param);

            OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderID);
            if (orderInfo.getState() != 1) {
                throw new ServiceException("订单已付款或已取消", RestConst.ErrorCode.DATABASE_ERROR);
            }
            OrderStateDto stateDto = new OrderStateDto();
            stateDto.setOrderID(orderInfo.getOrderID());
            stateDto.setState(2);
            stateDto.setPayTime(paytime);

            updateState(stateDto);

            //验证MD5加密信息
            int qty = orderItemMapper.selectqtyByOrderID(orderID);
            //成交金额为零
            BigDecimal amountTotal = BigDecimal.ZERO;
            //BigDecimal commission11 = orderItemMapper.selectSumCommissionByOrderID(orderID);
            Map<String, Double> commissionMap = orderItemMapper.selectTotalCommissionByOrderID(orderID);

            String md5 = CommonUtils.MD5(getAmountForMD5(amountTotal.toString()) + qty + ProConstants.salt);//md5加密
            Map<String, Object> param1 = new HashMap<String, Object>();
            param1.put("orderID", orderID);
            param1.put("qty", qty);
            param1.put("amount", amountTotal);
            //param1.put("commission", commission11);
            param1.put("commission", BigDecimal.valueOf(MapUtils.getDouble(commissionMap, "totalCommission", 0d)));
            param1.put("employeeCommission", BigDecimal.valueOf(MapUtils.getDouble(commissionMap, "totalEmployeeCommission", 0d)));
            param1.put("md5", md5);
            orderInfoMapper.updateAmountByPrimaryKey(param1);

            //抵扣金豆 added by tim peng 2017-4-6
            offsetQty = orderInfo.getPointAmount();
            para.put("amount", offsetQty);
            para.put("point", orderInfo.getPointQty());
            para.put("userID", orderInfo.getUserID());
            para.put("payNo", payNo);
        }

        if (offsetQty != null && offsetQty.compareTo(BigDecimal.ZERO) == 1 && !isOpenPointDeduction()) {
            throw new ServiceException("您选择的金豆抵现活动已下线,请重新选择或更新版本", RestConst.ErrorCode.DATABASE_ERROR);
        }
        if (offsetQty != null && offsetQty.compareTo(BigDecimal.ZERO) == 1) {
            DataResult result = HttpUtil.httpPost(ProConstants.setUseGoldenV2, para, restTemplate);
            logger.info("HttpUtil.httpPost......" + ProConstants.setUseGolden + "...........payno:" + payNo);
            if (result.getIsSuccess() == 0) {
                throw new ServiceException("调用point服务抵扣金豆失败,message=" + result.getErrorDesc(), RestConst.ErrorCode.SERVICE_FAIL);
            }
        }

        logger.info("complete zeroPay...........");
        return payNo;
    }


    /**
     * 获取预支付单号等信息
     *
     * @param orderIDList
     * @param payType     1微信支付 2建行支付 3支付宝 4JS微信支付 5
     * @return
     */
    public Object pay(List<Long> orderIDList, Integer payType, String userIp, String code) {
        if (payType == null || payType <= 0 || payType > 5) {
            throw new ServiceException("请选择正确的支付方式", RestConst.ErrorCode.FORM_FAIL);
        }
        logger.info("获取预支付单号payType={}", payType);
        String payNo = CodeGenerator.INSTANCE.nextId();
        BigDecimal amountTotal = BigDecimal.ZERO;
        String key = "payno" + payNo + userIp + payType;
        String payDesc = null;

        //用户提金运保费订单
        boolean isPointPay = false;
        Long orderid = null;
        for (Long orderID : orderIDList) {
            List<OrderItem> itemList = orderItemMapper.selectByOrderID(orderID);
            key = key + orderID;
            if (expireKey.exists(key)) {
                throw new ServiceException("您刚刚已经提交了，请勿重复操作");
            } else {
                expireKey.add(key);
            }
            if (itemList == null || itemList.isEmpty()) {
                DataResult result = HttpUtil.httpGet(ProConstants.getPointOrder + orderID, restTemplate);
                if (result.getIsSuccess() == 1 && result.getData() != null) {
                    isPointPay = true;
                    orderid = orderID;
                    Map pointMap = (Map) result.getData();
                    if (pointMap.get("fee") != null) {
                        amountTotal = amountTotal.add(new BigDecimal((String) pointMap.get("fee")));
                    } else {
                        amountTotal = BigDecimal.valueOf(1);
                    }
                    break;
                }
            }
            String exceptGoodsId = null;
            for (OrderItem orderItem : itemList) {
                GoodsInfoWithSkuDto goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuID(orderItem.getSkuID());
                if (goodsInfoWithSkuDto == null) {
                    throw new ServiceException("未查到商品SKU信息", RestConst.ErrorCode.DATABASE_ERROR);
                }
                if (!goodsInfoWithSkuDto.getState().equals("Shelve")) {
                    OrderStateDto stateDto = new OrderStateDto();
                    stateDto.setOrderID(orderID);
                    stateDto.setState(0);
                    updateState(stateDto);
                    throw new ServiceException("商品已下架，不能购买", RestConst.ErrorCode.DATABASE_ERROR);
                }
                if (payDesc == null) {
                    payDesc = orderItem.getGoodsName();
                }
                if ("0".equalsIgnoreCase(goodsInfoWithSkuDto.getOffsetFlag())) {
                    exceptGoodsId = getGoldenGoodsID();
                }
            }


            OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderID);
            if (orderInfo.getState() != 1) {
                throw new ServiceException("订单已付款或已取消", RestConst.ErrorCode.DATABASE_ERROR);
            }
            //丝绸之路商品不参与抵扣 added by tim peng 2017-5-24
            if (exceptGoodsId != null && orderInfo.getPointQty() != null && orderInfo.getPointQty().compareTo(BigDecimal.ZERO) == 1) {
                throw new ServiceException("此商品不参与抵现", RestConst.ErrorCode.FORM_FAIL);
            }
            if (!isOpenPointDeduction() && orderInfo.getPointQty().compareTo(BigDecimal.ZERO) == 1)
                throw new ServiceException("您选择的金豆抵现活动已下线,请重新选择或更新版本", RestConst.ErrorCode.DATABASE_ERROR);

            //如果payno存在则用回之前生成的，防止支付订单重复提交 2017-5-20
            if (orderInfo.getPayNo() != null && !StringUtils.isEmpty(orderInfo.getPayNo())) {
                payNo = orderInfo.getPayNo();
            }
            Map<String, Object> param = new HashMap<>();
            param.put("orderID", orderID);
            param.put("payNo", payNo);
            param.put("payType", payType);

            orderInfoMapper.updatePayNoByPrimaryKey(param);

            verifyMD5(orderID);   //验证MD5加密信息
            amountTotal = amountTotal.add(orderInfo.getAmount());
        }

        WxPayParamDto payParamDto = new WxPayParamDto();
        String payTitle = getPayTitle();
        payParamDto.setBody(payTitle == null ? "私享品" : payTitle);
        if (!StringUtils.isEmpty(payDesc)) {
            payParamDto.setBody((payTitle == null ? "私享品" : payTitle) + StringUtils.abbreviate(payDesc, 40));
        }
        // 预支付单号： payno+"X"+random
        payParamDto.setOut_trade_no(payNo + "X" + getRandByNum(5));
        payParamDto.setTotal_fee(getAmountForMD5(amountTotal.toString()));
        String paymentOnline = getPaymentOnline();
        if (paymentOnline != null && "0".equals(paymentOnline)) {
            //测试环境下支付1分
            payParamDto.setTotal_fee(getAmountForMD5("0.01"));//0.01
        }

        payParamDto.setSpbill_create_id(userIp);
        //这行很重要，类型识别
        payParamDto.setAttach("sxp." + SystemContext.getCompanyID());//赣州银行
        payParamDto.setResource(CommonUtils.MD5(payNo + ProConstants.paySalt));

        String notifyUrl = ProConstants.BANK + "/order/rePay";
        String wxpayMSUrl = ProConstants.PAYMENT + "/";
       /* ResultData dataResult = HttpUtil.httpGet_ResultData(ProConstants.BANKOPSSERVICE + "/sysConfig/getValToStr?companyID=" + SystemContext.getCompanyID() + "&code=ms.wxpay.notify", restTemplate);
        if ("1".equals(dataResult.getCode()) && dataResult.getData() != null) {
            notifyUrl = (String) dataResult.getData();
            if (StringUtils.endsWith(notifyUrl, "/")) {
                notifyUrl += "order/rePay";
            } else {
                notifyUrl += "/order/rePay";
            }
        } else {
            logger.error("ms.wxpay.notify在参数设置中不存在，将使用默认值");
        }
        dataResult = HttpUtil.httpGet_ResultData(ProConstants.BANKOPSSERVICE + "/sysConfig/getValToStr?companyID=" + SystemContext.getCompanyID() + "&code=ms.wxpay.url", restTemplate);
        if ("1".equals(dataResult.getCode()) && dataResult.getData() != null) {
            String tmp = (String) dataResult.getData();
            if (StringUtils.isEmpty(wxpayMSUrl)) {
                logger.error("ms.wxpay.url在参数设置中不存在，将使用默认值");
            } else if (!StringUtils.endsWith(tmp, "/")) {
                tmp += "/";
                wxpayMSUrl = tmp;
            } else {
                wxpayMSUrl = tmp;
            }
        } else {
            logger.error("ms.wxpay.urly在参数设置中不存在，将使用默认值");
        }*/

        payParamDto.setNotify(notifyUrl);
        payParamDto.setTimeOut(CommonUtils.getCurTimestamp() + "");
        payParamDto.setCompanyID(SystemContext.getCompanyID() + "");

        DataResult result = new DataResult();

        if (isPointPay) {
            Map para = new HashMap();
            para.put("pddetailId", orderid);
            para.put("pdpayNo", payNo);
            para.put("pdremark", "用户提金运保费用由微信支付");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("payType", "微信支付");//支付渠道类型名称
            jsonObject.put("payAmount", amountTotal);//支付金额
            jsonObject.put("payNum", payType);//支付类型
            para.put("pdextJSON", jsonObject.toString());
            result = HttpUtil.httpPost(ProConstants.updatePointPrepay, para, restTemplate);
            if (result.getIsSuccess() == 0) {
                throw new ServiceException("用户提金运保费用由微信支付,生成预支付单号失败", RestConst.ErrorCode.DATABASE_ERROR);
                //logger.error("用户提金运保费用由微信支付,生成预支付单号失败.para:" + para.toString());
            }
        }

        logger.info("payParam={}", payParamDto);

        switch (payType) {
            case 1:
                payParamDto.setType("1");
                result = HttpUtil.httpPost(wxpayMSUrl + ProConstants.URL_WXPAY_APP, payParamDto, restTemplate);
                break;
            case 2:
                payParamDto.setType("2");
                result = HttpUtil.httpPost(ProConstants.getCCBPayURL, payParamDto, restTemplate);
                break;
            case 4:
                payParamDto.setType("4");
                payParamDto.setCode(code);
                result = HttpUtil.httpPost(wxpayMSUrl + ProConstants.URL_WXPAY_JS, payParamDto, restTemplate);
                break;
            case 5:
                payParamDto.setType("5");
                result = HttpUtil.httpPost(ProConstants.getCCBH5PayURL, payParamDto, restTemplate);
                break;
        }
        if (result.getIsSuccess() != 1) {
            throw new ServiceException("调用支付服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        return result.getData();
    }

    public Object payForGz(GzPayDto gzPayDto, Integer payType, String userIp, String code) {
        List<Long> orderIDList = gzPayDto.getOrderids();
        if (payType == null || payType <= 0 || payType > 5) {
            throw new ServiceException("请选择正确的支付方式", RestConst.ErrorCode.FORM_FAIL);
        }
        logger.info("获取预支付单号payType={}", payType);
        String payNo = CodeGenerator.INSTANCE.nextId();
        BigDecimal amountTotal = BigDecimal.ZERO;
        BigDecimal pointAmountTotal = BigDecimal.ZERO;
        String key = "payno" + payNo + userIp + payType;
        String payDesc = null;

        //用户提金运保费订单
        //boolean isPointPay = false;
        Long orderid = null;
        for (Long orderID : orderIDList) {
            List<OrderItem> itemList = orderItemMapper.selectByOrderID(orderID);
            key = key + orderID;
            if (expireKey.exists(key)) {
                throw new ServiceException("您刚刚已经提交了，请勿重复操作");
            } else {
                expireKey.add(key);
            }
            /*if (itemList == null || itemList.isEmpty()) {
                DataResult result = HttpUtil.httpGet(ProConstants.getPointOrder + orderID, restTemplate);
                if (result.getIsSuccess() == 1 && result.getData() != null) {
                    isPointPay = true;
                    orderid = orderID;
                    Map pointMap = (Map) result.getData();
                    if (pointMap.get("fee") != null) {
                        amountTotal = amountTotal.add(new BigDecimal((String) pointMap.get("fee")));
                    } else {
                        amountTotal = BigDecimal.valueOf(1);
                    }
                    break;
                }
            }*/
            String exceptGoodsId = null;
            for (OrderItem orderItem : itemList) {
                GoodsInfoWithSkuDto goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuID(orderItem.getSkuID());
                if (goodsInfoWithSkuDto == null) {
                    throw new ServiceException("未查到商品SKU信息", RestConst.ErrorCode.DATABASE_ERROR);
                }
                if (!goodsInfoWithSkuDto.getState().equals("Shelve")) {
                    OrderStateDto stateDto = new OrderStateDto();
                    stateDto.setOrderID(orderID);
                    stateDto.setState(0);
                    updateState(stateDto);
                    throw new ServiceException("商品已下架，不能购买", RestConst.ErrorCode.DATABASE_ERROR);
                }
                if (payDesc == null) {
                    payDesc = orderItem.getGoodsName();
                }
                if ("0".equalsIgnoreCase(goodsInfoWithSkuDto.getOffsetFlag())) {
                    exceptGoodsId = getGoldenGoodsID();
                }
            }


            OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderID);
            if (orderInfo.getState() != 1) {
                throw new ServiceException("订单已付款或已取消", RestConst.ErrorCode.DATABASE_ERROR);
            }
            //丝绸之路商品不参与抵扣 added by tim peng 2017-5-24
           /* if (exceptGoodsId != null && orderInfo.getPointQty() != null && orderInfo.getPointQty().compareTo(BigDecimal.ZERO) == 1) {
                throw new ServiceException("此商品不参与抵现", RestConst.ErrorCode.FORM_FAIL);
            }
            if (!isOpenPointDeduction() && orderInfo.getPointQty().compareTo(BigDecimal.ZERO) == 1)
                throw new ServiceException("您选择的金豆抵现活动已下线,请重新选择或更新版本", RestConst.ErrorCode.DATABASE_ERROR);*/

            //如果payno存在则用回之前生成的，防止支付订单重复提交 2017-5-20
            if (orderInfo.getPayNo() != null && !StringUtils.isEmpty(orderInfo.getPayNo())) {
                payNo = orderInfo.getPayNo();
            }
            Map<String, Object> param = new HashMap<>();
            param.put("orderID", orderID);
            param.put("payNo", payNo);
            param.put("payType", payType);

            orderInfoMapper.updatePayNoByPrimaryKey(param);

            verifyMD5(orderID);   //验证MD5加密信息
            amountTotal = amountTotal.add(orderInfo.getAmount());
            pointAmountTotal = BigDecimalUtil.add(orderInfo.getPointAmount(), pointAmountTotal);
        }

        WxPayParamDto payParamDto = new WxPayParamDto();
        String payTitle = getPayTitle();
        payParamDto.setBody(payTitle == null ? "私享品" : payTitle);
        if (!StringUtils.isEmpty(payDesc)) {
            payParamDto.setBody((payTitle == null ? "私享品" : payTitle) + StringUtils.abbreviate(payDesc, 40));
        }
        // 预支付单号： payno+"X"+random
        payParamDto.setOut_trade_no(payNo + "X" + getRandByNum(5));//支付成功，变成支付单号
        payParamDto.setTotal_fee(getAmountForMD5(amountTotal.toString()));
        payParamDto.setDiscountAmount(pointAmountTotal.toString());
        String paymentOnline = getPaymentOnline();
        if (paymentOnline != null && "0".equals(paymentOnline)) {
            //测试环境下支付1分
            payParamDto.setTotal_fee(getAmountForMD5("0.01"));//0.01
        }

        payParamDto.setSpbill_create_id(userIp);
        //这行很重要，类型识别
        payParamDto.setAttach("gzb." + SystemContext.getCompanyID());
        payParamDto.setResource(CommonUtils.MD5(payNo + ProConstants.paySalt));

        String notifyUrl = ProConstants.BANK + "/order/rePay";
        String wxpayMSUrl = ProConstants.PAYMENT;
        ResultData dataResult = HttpUtil.httpGet_ResultData(ProConstants.BANKOPSSERVICE + "/sysConfig/getValToStr?companyID=" + SystemContext.getCompanyID() + "&code=ms.wxpay.notify", restTemplate);
        if ("1".equals(dataResult.getCode()) && dataResult.getData() != null) {
            notifyUrl = (String) dataResult.getData();
            if (StringUtils.endsWith(notifyUrl, "/")) {
                notifyUrl += "order/rePay";
            } else {
                notifyUrl += "/order/rePay";
            }
        } else {
            logger.error("ms.wxpay.notify在参数设置中不存在，将使用默认值");
        }
        dataResult = HttpUtil.httpGet_ResultData(ProConstants.BANKOPSSERVICE + "/sysConfig/getValToStr?companyID=" + SystemContext.getCompanyID() + "&code=ms.wxpay.url", restTemplate);
        if ("1".equals(dataResult.getCode()) && dataResult.getData() != null) {
            String tmp = (String) dataResult.getData();
            if (StringUtils.isEmpty(wxpayMSUrl)) {
                logger.error("ms.wxpay.url在参数设置中不存在，将使用默认值");
            } else if (!StringUtils.endsWith(tmp, "/")) {
                tmp += "/";
                wxpayMSUrl = tmp;
            } else {
                wxpayMSUrl = tmp;
            }
        } else {
            logger.error("ms.wxpay.urly在参数设置中不存在，将使用默认值");
        }

        payParamDto.setNotify(notifyUrl);

        payParamDto.setTimeOut(CommonUtils.getCurTimestamp() + "");
        payParamDto.setCompanyID(SystemContext.getCompanyID() + "");

        DataResult result = new DataResult();

        logger.info("payParam={}", payParamDto);
        payParamDto.setJumpUrl(gzPayDto.getJumpUrl());
        switch (payType) {
            case 1:
                payParamDto.setType("1");
                result = HttpUtil.httpPost(wxpayMSUrl + ProConstants.URL_WXPAY_APP_FORGZ, payParamDto, restTemplate);
                break;
            case 2:
              /*  payParamDto.setType("2");
                result = HttpUtil.httpPost(ProConstants.getCCBPayURL, payParamDto, restTemplate);*/
                break;
            case 4:
                payParamDto.setType("4");
                payParamDto.setCode(code);
                result = HttpUtil.httpPost(wxpayMSUrl + ProConstants.URL_WXPAY_JS_FORGZ, payParamDto, restTemplate);
                break;
            case 5:
               /* payParamDto.setType("5");
                result = HttpUtil.httpPost(ProConstants.getCCBH5PayURL, payParamDto, restTemplate);*/
                break;
        }
        if (result.getIsSuccess() != 1) {
            throw new ServiceException("调用支付服务出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        return result.getData();
    }

    private BigDecimal getTransactionFee(BigDecimal amount, Integer payType) {
        //微信6/1000,龙支付2.5/1000
        PayFeeEnum payFeeEnum = PayFeeEnum.valuekOf(payType);
        if (amount == null) {
            amount = BigDecimal.valueOf(0);
        }
        BigDecimal tFee = BigDecimalUtil.mul(amount, payFeeEnum.getThousand());
        BigDecimal fee = BigDecimalUtil.div(tFee, BigDecimal.valueOf(1000), 4);
        return fee;
    }

    private BigDecimal getOtherFee() {
        try {
            String otherFee = CommonTools.getExtString(restTemplate, ProConstants.otherFeeCode);
            Double d = Doubles.tryParse(otherFee);
            if (d == null) {
                d = 0d;
            }
            BigDecimal fee = BigDecimal.valueOf(d);
            return fee;
        } catch (Exception e) {
            //e.printStackTrace();
            return BigDecimal.ZERO;
        } catch (Error e) {
            //e.printStackTrace();
            return BigDecimal.ZERO;
        }
    }


    //支付回调
    public synchronized Object rePay(final WxPayResultDto resultDto) {
        String md5 = CommonUtils.MD5(resultDto.getOrderNo() + ProConstants.paySalt);
        if (!resultDto.getMd5String().equals(md5)) {
            throw new ServiceException("加密信息失败", RestConst.ErrorCode.SERVICE_FAIL);
        }
        if (resultDto.getIsSuccess().equals("success")) {
            String tempPayNO = resultDto.getOrderNo();
            if (tempPayNO.indexOf("X") > 0) {
                resultDto.setOrderNo(tempPayNO.substring(0, tempPayNO.indexOf("X")));
            }
            List<OrderInfo> infoList = orderInfoMapper.selectByPayNo(resultDto.getOrderNo());
            if (infoList.size() > 0) {
                //用户购买商品订单
                Long tempUserId = 0l;
                String orderNO = "";
                Long paytime = CommonUtils.getCurTimestamp();
                for (OrderInfo orderInfo : infoList) {
                    OrderStateDto stateDto = new OrderStateDto();
                    stateDto.setOrderID(orderInfo.getOrderID());
                    stateDto.setState(2);
                    stateDto.setPayTime(paytime);
                    stateDto.setPayNO(tempPayNO);//
                    //add by wanglq for 手续费
                    stateDto.setTransactionFee(getTransactionFee(orderInfo.getAmount(), orderInfo.getPayType()));
                    stateDto.setOtherFee(getOtherFee());

                    //回调成功写回db
                    orderInfo.setPayNo(tempPayNO);
                    updateState(stateDto);
                    if (tempUserId == 0) {
                        tempUserId = orderInfo.getUserID();
                    }
                    //截取尾数6位
                    orderNO += StringUtils.right(orderInfo.getOrderNO(), 6) + ",";
                    orderInfo.setTransactionFee(stateDto.getTransactionFee());
                    orderInfo.setOtherFee(stateDto.getOtherFee());
                }
                //生成金豆及其佣金信息

                if (isOpenGoldPoint()) {
                    //setPointV2(tempPayNO);
                    logger.info("................生成金豆及其佣金信息...................");
                    commissionUserService.addCommissionForNoException(infoList, tempPayNO, restTemplate);
                }
                //发送通知短信 added by pengzh 2017-3-17
                if (tempUserId > 0 && "1".equals(getNoticeSMS())) {
                    if (orderNO != null && StringUtils.contains(orderNO, ",")) {
                        orderNO = StringUtils.left(orderNO, orderNO.length() - 1);
                    }
                    UserInfoForOrderDto usedto = (UserInfoForOrderDto) getUserInfoForOrder(tempUserId);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("mobile", usedto.getMobile()); //下单人手机
                    jsonObject.put("type", SmsTempEnum.PAY_SUCCESS.getCode());//支付成功通知
                    jsonObject.put("param", new String[]{orderNO, CommonUtils.formatDateTime(new Date(paytime), "yyyy-MM-dd HH:mm:ss")});
                    DataResult result = HttpUtil.httpPost(ProConstants.SMS + "/notice", jsonObject, restTemplate);
                    if (result.getIsSuccess() != 1) {
                        logger.error("调用短信服务失败:" + result.getErrorDesc());
                    }

                }

                // 分配奖金
                //erp开关
                if (!isOpenErp()) {
                    //commissionUserService.addCommissionForNoException(infoList, tempPayNO, restTemplate);
                    return "success";
                }

                boolean isErp = sendForErp(infoList, tempPayNO);
                commissionUserService.addCommissionForNoException(infoList, tempPayNO, restTemplate);
                if (isErp) {
                    logger.info("对接ERP信息成功,(PayNo)单号为" + tempPayNO);
                } else {
                    JSONObject jsonObject = new JSONObject();
                    //getTelephone
                    jsonObject.put("mobile", CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.TELEPHONE.getCode())); //下单人手机
                    jsonObject.put("type", SmsTempEnum.ERP_EXCEPTION.getCode());
                    jsonObject.put("param", new String[]{"对接ERP订单信息失败:PayNo单号为" + resultDto.getOrderNo()});
                    DataResult result = HttpUtil.httpPost(ProConstants.SMS + "/notice", jsonObject, restTemplate);
                    if (result.getIsSuccess() != 1) {
                        logger.error("发送短信失败");
                    }
                    ErrErpOrder errErpOrder = new ErrErpOrder();
                    errErpOrder.setErrorId(IdGen.get().nextId());
                    errErpOrder.setPayNo(resultDto.getOrderNo());//实际存的是payNo
                    errErpOrder.setAddTime(System.currentTimeMillis());
                    errErpOrder.setState("0");
                    errErpOrderMapper.insertSelective(errErpOrder);
                    logger.error("对接ERP信息失败,PayNo单号为" + tempPayNO);
                }
                return "success";
            } else {
                //用户提金运保费订单
                DataResult result = HttpUtil.httpGet(ProConstants.getPointPayNO + resultDto.getOrderNo(), restTemplate);
                if (result.getIsSuccess() == 1 && result.getData() != null) {
                    Map map = (Map) result.getData();
                    String pointPayOrderId = (String) map.get("detailId");
                    result = HttpUtil.httpGet(ProConstants.updatePointPay + pointPayOrderId + "/" + tempPayNO, restTemplate);
                    if (result.getIsSuccess() == 0) {
                        //throw new ServiceException("用户提金运保费订单支付回调失败,id:" + resultDto.getOrderNo(), RestConst.ErrorCode.SERVICE_FAIL);
                        logger.error("用户提金运保费订单支付回调失败,id:" + resultDto.getOrderNo());
                    } else {

                        //提金运保费订单加入ES Index
                        OrderIndexDto freight = new OrderIndexDto();
                        freight.setPayNO(tempPayNO);
                        freight.setOrderID(pointPayOrderId);
                        freight.setOrderNO(resultDto.getOrderNo());
                        freight.setAmount(new BigDecimal((String) map.get("fee")));
                        freight.setPayTime(CommonUtils.getCurTimestamp() + "");
                        String pdextJSON = (String) map.get("pdextJSON");
                        JSONObject js = JSONObject.fromObject(pdextJSON);
                        freight.setPayType(js.getInt("payNum"));//wechat jsPay
                        freight.setBuyersName((String) map.get("receipt"));
                        freight.setAddress((String) map.get("address"));
                        UserInfoForOrderDto userInfoForOrderDto = (UserInfoForOrderDto) getUserInfoForOrder(Long.valueOf((String) map.get("pduserId")));
                        String mobile = userInfoForOrderDto.getMobile();
                        freight.setMobile(mobile);
                        freight.setOrderType("2");
                        freight.setStatus(2);
                        freight.setBuyersID((String) map.get("pduserId"));
                        freight.setAddTime(((String) map.get("pdhandleTime")));
                        freight.setOrderItem(new ArrayList<OrderItemIndexDto>());
                        DataResult resultFreight = HttpUtil.httpPost(ProConstants.ESURL + "/order/newIndex", freight, restTemplate);
                        if (resultFreight.getIsSuccess() != 1) {
                            logger.error("提金运保费订单新建索引失败,orderID=" + resultDto.getOrderNo() + ",message:" + resultFreight.getErrorDesc());
                            //throw new ServiceException("新建索引失败", RestConst.ErrorCode.SERVICE_FAIL);
                        }

                        // save 提金运保费 to db
                        OrderInfo orderInfo = new OrderInfo();
                        orderInfo.setPayNo(tempPayNO);
                        orderInfo.setOrderID(IdGen.get().nextId());
                        orderInfo.setOrderNO(resultDto.getOrderNo()); //
                        orderInfo.setAddTime(CommonUtils.getCurTimestamp());
                        orderInfo.setReceiverAddress((String) map.get("address"));
                        orderInfo.setAmount(new BigDecimal((String) map.get("fee")));
                        orderInfo.setPayTime(CommonUtils.getCurTimestamp());
                        orderInfo.setPayType(4);//wechat jsPay
                        orderInfo.setReceiverName((String) map.get("receipt"));
                        orderInfo.setReceiverPhone(mobile);
                        orderInfo.setOrderType(2);
                        orderInfo.setUserName((String) map.get("receipt"));
                        orderInfo.setState(2);
                        orderInfo.setInvoicesType(0);
                        orderInfo.setInvoices(0);
                        orderInfo.setCouponType("1");
                        orderInfo.setPointQty(BigDecimal.ZERO);
                        orderInfo.setPointAmount(BigDecimal.ZERO);
                        orderInfo.setqty(1);
                        //companyID待定 2017-7-12
                        orderInfo.setCompanyID(SystemContext.getCompanyID());
                        orderInfo.setUserID(Long.valueOf((String) map.get("pduserId")));

                        orderInfoMapper.insertSelective(orderInfo);

                        OrderItem orderItem = new OrderItem();
                        orderItem.setItemID(IdGen.get().nextId());
                        orderItem.setOrderID(orderInfo.getOrderID());
                        orderItem.setQty(1);
                        orderItem.setSkuID(10000l);
                        orderItem.setGoodsID(10000l);
                        orderItem.setGoodsName("提金运保费");
                        orderItem.setAmount(orderInfo.getAmount());
                        orderItem.setPrice(orderInfo.getAmount());
                        orderItem.setMemo("提金运保费");
                        orderItem.setSeqno(1);

                        orderItemMapper.insertSelective(orderItem);
                    }
                } else {
                    logger.error("未查到该支付单号的信息,payno:" + tempPayNO);
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("mobile", CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.TELEPHONE.getCode())); //下单人手机
                    jsonObject.put("type", SmsTempEnum.ERP_EXCEPTION.getCode());
                    jsonObject.put("param", new String[]{"支付回调失败单号:" + resultDto.getOrderNo()});
                    HttpUtil.httpPost(ProConstants.SMS + "/notice", jsonObject, restTemplate);
                }
                return "success";
            }
        } else {
            throw new ServiceException("支付回调失败", RestConst.ErrorCode.SERVICE_FAIL);
        }

    }


    /**
     * 产生num位的随机数
     *
     * @return
     */
    public static String getRandByNum(int num) {
        String length = "1";
        for (int i = 0; i < num; i++) {
            length += "0";
        }

        Random rad = new Random();

        String result = rad.nextInt(Integer.parseInt(length)) + "";

        if (result.length() != num) {
            return getRandByNum(num);
        }
        return result;
    }

    public void receive(Long orderID) {
        OrderStateDto orderStateDto = new OrderStateDto();
        orderStateDto.setOrderID(orderID);
        orderStateDto.setState(4);
        boolean result = this.updateState(orderStateDto);
        if (result && isOpenErp()) {
            //getConfirmSendOrder ==  getSecretKey
            ResultData resultData = OrderController.httpGet(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.CONFIRMSENDORDER.getCode()) + "?orderNO=" + orderID, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SECRETKEY.getCode()));
            if (!com.google.common.base.Objects.equal("1", resultData.getCode())) {
                OrderIndexStateDto indexStateDto = new OrderIndexStateDto();
                indexStateDto.setOrderID(orderID + "");
                indexStateDto.setStatus(3);
                orderIndexService.updateState(indexStateDto);
                throw new ServiceException("收货失败");
            }
        }

    }


    //修改状态
    public synchronized boolean updateState(final OrderStateDto stateDto) {
        try {
            OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(stateDto.getOrderID());
            if (orderInfo == null) {
                throw new ServiceException("订单不存在", RestConst.ErrorCode.DATABASE_ERROR);
            }
            switch (stateDto.getState()) {
                case 0:   //取消订单、加库存、修改索引状态
                    OrderInfo order = orderInfoMapper.selectByPrimaryKey(stateDto.getOrderID());
                    if (order.getState() != 1) {
                        throw new ServiceException("订单状态参数传入有误，不能取消", RestConst.ErrorCode.FORM_FAIL);
                    }
                    verifyMD5(stateDto.getOrderID());  //验证MD5加密信息
                    List<OrderItem> itemList = orderItemMapper.selectByOrderID(stateDto.getOrderID());
                    for (OrderItem item : itemList) {
                        goodsService.changeInventory(0, item.getGoodsID(), item.getSkuID(), item.getQty(), item.getItemID());
                    }

                    OrderIndexStateDto indexStateDto3 = new OrderIndexStateDto();
                    indexStateDto3.setOrderID(stateDto.getOrderID().toString());
                    indexStateDto3.setStatus(0);

                    stateDto.setState(0);
                    orderInfoMapper.updateStateByPrimaryKey(stateDto);
                    orderIndexService.updateState(indexStateDto3);

                    //取消优惠券
                    cancelCoupon(order.getOrderID());
                    break;

                case 2: //付款完成、增加销量、修改索引状态
                    OrderInfo order1 = orderInfoMapper.selectByPrimaryKey(stateDto.getOrderID());
                    if (order1.getState() != 1) {
                        throw new ServiceException("订单状态参数传入有误，不能付款", RestConst.ErrorCode.FORM_FAIL);
                    }
                    verifyMD5(stateDto.getOrderID());  //验证MD5加密信息
                    stateDto.setPayTime(CommonUtils.getCurTimestamp());
                    List<OrderItem> orderItemList = orderItemMapper.selectByOrderID(stateDto.getOrderID());
                    for (OrderItem item : orderItemList) {
                        goodsService.changeInventory(2, item.getGoodsID(), item.getSkuID(), item.getQty(), item.getItemID());
                    }
                    OrderIndexStateDto indexStateDto = new OrderIndexStateDto();
                    indexStateDto.setOrderID(stateDto.getOrderID().toString());
                    indexStateDto.setStatus(2);
                    indexStateDto.setPayTime(System.currentTimeMillis() + "");
                    indexStateDto.setPayType(order1.getPayType());
                    indexStateDto.setPayNO(stateDto.getPayNO());

                    stateDto.setState(2);
                    orderInfoMapper.updateStateByPrimaryKey(stateDto);
                    orderIndexService.updateState(indexStateDto);
                    break;

                case 3: //已发货
                    OrderInfo order2 = orderInfoMapper.selectByPrimaryKey(stateDto.getOrderID());
                    if (order2.getState() != 5) {
                        throw new ServiceException("订单状态参数传入有误，不能发货", RestConst.ErrorCode.FORM_FAIL);
                    }
                    OrderLogistics orderLogistics = orderLogisticsMapper.selectByOrderID(stateDto.getOrderID());
                    if (orderLogistics == null) {
                        throw new ServiceException("请先添加物流运单号信息", RestConst.ErrorCode.DATABASE_ERROR);
                    }
                    verifyMD5(stateDto.getOrderID());  //验证MD5加密信息
                    stateDto.setSendTime(CommonUtils.getCurTimestamp());

                    OrderIndexStateDto indexStateDto1 = new OrderIndexStateDto();
                    indexStateDto1.setOrderID(stateDto.getOrderID().toString());
                    indexStateDto1.setStatus(3);

                    indexStateDto1.setPayTime(order2.getPayTime() + "");
                    indexStateDto1.setPayType(order2.getPayType());
                    indexStateDto1.setSendTime(System.currentTimeMillis() + "");
                    indexStateDto1.setSureTime(order2.getSureTime() + "");
                    indexStateDto1.setPayNO(order2.getPayNo());


                    logger.info("order2.getCompanyID()===" + order2.getCompanyID());
                    ResultData isData = HttpUtil.httpGet_ResultData_headers(ProConstants.getExtString + "?companyID=" + order2.getCompanyID() + "&code=" + "noticeSMS", restTemplate, order2.getCompanyID());
                    //短信开启
                    if ("1".equals(isData.getData())) {
                        //create by zll
                        String mobile = order2.getReceiverPhone();
//                        String mobile = addMap.get("contactPhone"); //update by zll
                        if (!mobile.equalsIgnoreCase("未查到") && orderLogistics.getBilNumber() != null && orderLogistics.getCompany() != null) {
                            //发送通知短信 added by pengzh 2017-3-17
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("mobile", mobile); //下单人手机
                            jsonObject.put("type", SmsTempEnum.SENDNOTICE.getCode());//发货通知
                            jsonObject.put("param", new String[]{orderLogistics.getCompany(), orderLogistics.getBilNumber()});
                            DataResult result = HttpUtil.httpPost_headers(ProConstants.SMS + "/notice", jsonObject, restTemplate, order2.getCompanyID());
                            if (result.getIsSuccess() != 1) {
                                //throw new ServiceException("调用短信服务失败", RestConst.ErrorCode.SERVICE_FAIL);
                                logger.error("调用短信服务失败:" + result.getErrorDesc());
                            }
                            if (logger.isInfoEnabled()) {
                                logger.info("发送express通知短信ok.... " + mobile);
                            }

                        }
                    }
                    stateDto.setState(3);
                    orderInfoMapper.updateStateByPrimaryKey(stateDto);
                    orderIndexService.updateState(indexStateDto1);
                    break;

                case 4:  //确认收货、订单完成
                    OrderInfo order3 = orderInfoMapper.selectByPrimaryKey(stateDto.getOrderID());
                    if (order3.getState() != 3) {
                        throw new ServiceException("订单状态参数传入有误，不能确认收货", RestConst.ErrorCode.FORM_FAIL);
                    }
                    verifyMD5(stateDto.getOrderID());  //验证MD5加密信息
                    stateDto.setFinishTime(CommonUtils.getCurTimestamp());

                    OrderIndexStateDto indexStateDto2 = new OrderIndexStateDto();
                    indexStateDto2.setOrderID(stateDto.getOrderID().toString());
                    indexStateDto2.setStatus(4);

                    indexStateDto2.setPayTime(order3.getPayTime() + "");
                    indexStateDto2.setPayType(order3.getPayType());
                    indexStateDto2.setSendTime(order3.getSendTime() + "");
                    indexStateDto2.setFinishTime(System.currentTimeMillis() + "");
                    indexStateDto2.setSureTime(order3.getSureTime() + "");
                    indexStateDto2.setPayNO(order3.getPayNo());

                    stateDto.setState(4);
                    orderInfoMapper.updateStateByPrimaryKey(stateDto);
                    orderIndexService.updateState(indexStateDto2);
                    break;
                case 5:  //卖家发货前确认
                    OrderInfo order5 = orderInfoMapper.selectByPrimaryKey(stateDto.getOrderID());
                    if (order5.getState() != 2) {
                        throw new ServiceException("订单状态参数传入有误，不能确认", RestConst.ErrorCode.FORM_FAIL);
                    }
                    verifyMD5(stateDto.getOrderID());  //验证MD5加密信息
                    stateDto.setSureTime(CommonUtils.getCurTimestamp());

                    OrderIndexStateDto indexStateDto4 = new OrderIndexStateDto();
                    indexStateDto4.setOrderID(stateDto.getOrderID().toString());
                    indexStateDto4.setStatus(5);
                    indexStateDto4.setPayTime(order5.getPayTime() + "");
                    indexStateDto4.setPayType(order5.getPayType());
                    indexStateDto4.setSendTime("0");
                    indexStateDto4.setFinishTime("0");
                    indexStateDto4.setSureTime(System.currentTimeMillis() + "");
                    indexStateDto4.setPayNO(order5.getPayNo());
                    if (isOpenGoldPoint() && order5.getOrderPayType() != null && order5.getOrderPayType() == 1)
                        setPointV2(order5.getPayNo());

                    stateDto.setState(5);
                    orderInfoMapper.updateStateByPrimaryKey(stateDto);
                    orderIndexService.updateState(indexStateDto4);
                    break;

                default:
                    throw new ServiceException("状态参数传入有误", RestConst.ErrorCode.FORM_FAIL);
            }
            //orderInfoMapper.updateStateByPrimaryKey(stateDto);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("修改状态失败：", e);
        }
        return true;
    }


    public boolean updateState2(final OrderStateDto stateDto) {
        try {
            OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(stateDto.getOrderID());
            if (orderInfo == null) {
                throw new ServiceException("订单不存在", RestConst.ErrorCode.DATABASE_ERROR);
            }
            switch (stateDto.getState()) {
                case 0:   //取消订单、加库存、修改索引状态
                    OrderInfo order = orderInfoMapper.selectByPrimaryKey(stateDto.getOrderID());
                    if (order.getState() != 1) {
                        throw new ServiceException("订单状态参数传入有误，不能取消", RestConst.ErrorCode.FORM_FAIL);
                    }
                    //verifyMD5(stateDto.getOrderID());  //验证MD5加密信息
                    List<OrderItem> itemList = orderItemMapper.selectByOrderID(stateDto.getOrderID());
                    for (OrderItem item : itemList) {
                        goodsService.changeInventory(0, item.getGoodsID(), item.getSkuID(), item.getQty(), item.getItemID());
                    }

                    OrderIndexStateDto indexStateDto3 = new OrderIndexStateDto();
                    indexStateDto3.setOrderID(stateDto.getOrderID().toString());
                    indexStateDto3.setStatus(0);

                    stateDto.setState(0);
                    orderInfoMapper.updateStateByPrimaryKey(stateDto);
                    orderIndexService.updateState(indexStateDto3);

                    //取消优惠券
                    cancelCoupon(order.getOrderID());

                    break;

                case 2: //付款完成、增加销量、修改索引状态
                    OrderInfo order1 = orderInfoMapper.selectByPrimaryKey(stateDto.getOrderID());
                    if (order1.getState() != 1) {
                        throw new ServiceException("订单状态参数传入有误，不能付款", RestConst.ErrorCode.FORM_FAIL);
                    }
                    //verifyMD5(stateDto.getOrderID());  //验证MD5加密信息
                    stateDto.setPayTime(CommonUtils.getCurTimestamp());
                    List<OrderItem> orderItemList = orderItemMapper.selectByOrderID(stateDto.getOrderID());
                    for (OrderItem item : orderItemList) {
                        goodsService.changeInventory(2, item.getGoodsID(), item.getSkuID(), item.getQty(), item.getItemID());
                    }
                    OrderIndexStateDto indexStateDto = new OrderIndexStateDto();
                    indexStateDto.setOrderID(stateDto.getOrderID().toString());
                    indexStateDto.setStatus(2);
                    indexStateDto.setPayTime(System.currentTimeMillis() + "");
                    indexStateDto.setPayType(order1.getPayType());
                    indexStateDto.setPayNO(stateDto.getPayNO());
                    stateDto.setState(2);
                    orderInfoMapper.updateStateByPrimaryKey(stateDto);
                    orderIndexService.updateState(indexStateDto);
                    break;

                case 3: //已发货
                    OrderInfo order2 = orderInfoMapper.selectByPrimaryKey(stateDto.getOrderID());
                    if (order2.getState() != 5) {
                        throw new ServiceException("订单状态参数传入有误，不能发货", RestConst.ErrorCode.FORM_FAIL);
                    }
                    OrderLogistics orderLogistics = orderLogisticsMapper.selectByOrderID(stateDto.getOrderID());
                    if (orderLogistics == null) {
                        throw new ServiceException("请先添加物流运单号信息", RestConst.ErrorCode.DATABASE_ERROR);
                    }
                    //verifyMD5(stateDto.getOrderID());  //验证MD5加密信息
                    stateDto.setSendTime(CommonUtils.getCurTimestamp());

                    OrderIndexStateDto indexStateDto1 = new OrderIndexStateDto();
                    indexStateDto1.setOrderID(stateDto.getOrderID().toString());
                    indexStateDto1.setStatus(3);

                    indexStateDto1.setPayTime(order2.getPayTime() + "");
                    indexStateDto1.setPayType(order2.getPayType());
                    indexStateDto1.setSendTime(System.currentTimeMillis() + "");
                    indexStateDto1.setSureTime(order2.getSureTime() + "");
                    indexStateDto1.setPayNO(order2.getPayNo());


                    logger.info("order2.getCompanyID()===" + order2.getCompanyID());
                    ResultData isData = HttpUtil.httpGet_ResultData_headers(ProConstants.getExtString + "?companyID=" + order2.getCompanyID() + "&code=" + "noticeSMS", restTemplate, order2.getCompanyID());
                    //短信开启
                    if ("1".equals(isData.getData())) {
                        //create by zll
                        String mobile = order2.getReceiverPhone();
//                        String mobile = addMap.get("contactPhone"); //update by zll
                        if (!mobile.equalsIgnoreCase("未查到") && orderLogistics.getBilNumber() != null && orderLogistics.getCompany() != null) {
                            //发送通知短信 added by pengzh 2017-3-17
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("mobile", mobile); //下单人手机
                            jsonObject.put("type", SmsTempEnum.SENDNOTICE.getCode());//发货通知
                            jsonObject.put("param", new String[]{orderLogistics.getCompany(), orderLogistics.getBilNumber()});
                            DataResult result = HttpUtil.httpPost_headers(ProConstants.SMS + "/notice", jsonObject, restTemplate, order2.getCompanyID());
                            if (result.getIsSuccess() != 1) {
                                //throw new ServiceException("调用短信服务失败", RestConst.ErrorCode.SERVICE_FAIL);
                                logger.error("调用短信服务失败:" + result.getErrorDesc());
                            }
                            if (logger.isInfoEnabled()) {
                                logger.info("发送express通知短信ok.... " + mobile);
                            }

                        }
                    }
                    stateDto.setState(3);
                    orderInfoMapper.updateStateByPrimaryKey(stateDto);
                    orderIndexService.updateState(indexStateDto1);
                    break;

                case 4:  //确认收货、订单完成
                    OrderInfo order3 = orderInfoMapper.selectByPrimaryKey(stateDto.getOrderID());
                    if (order3.getState() != 3) {
                        throw new ServiceException("订单状态参数传入有误，不能确认收货", RestConst.ErrorCode.FORM_FAIL);
                    }
                    //verifyMD5(stateDto.getOrderID());  //验证MD5加密信息
                    stateDto.setFinishTime(CommonUtils.getCurTimestamp());

                    OrderIndexStateDto indexStateDto2 = new OrderIndexStateDto();
                    indexStateDto2.setOrderID(stateDto.getOrderID().toString());
                    indexStateDto2.setStatus(4);

                    indexStateDto2.setPayTime(order3.getPayTime() + "");
                    indexStateDto2.setPayType(order3.getPayType());
                    indexStateDto2.setSendTime(order3.getSendTime() + "");
                    indexStateDto2.setFinishTime(System.currentTimeMillis() + "");
                    indexStateDto2.setSureTime(order3.getSureTime() + "");
                    indexStateDto2.setPayNO(order3.getPayNo());

                    stateDto.setState(4);
                    orderInfoMapper.updateStateByPrimaryKey(stateDto);
                    orderIndexService.updateState(indexStateDto2);

                    break;
                case 5:  //卖家发货前确认
                    OrderInfo order5 = orderInfoMapper.selectByPrimaryKey(stateDto.getOrderID());
                    if (order5.getState() != 2) {
                        throw new ServiceException("订单状态参数传入有误，不能确认", RestConst.ErrorCode.FORM_FAIL);
                    }
                    //verifyMD5(stateDto.getOrderID());  //验证MD5加密信息
                    stateDto.setSureTime(CommonUtils.getCurTimestamp());

                    OrderIndexStateDto indexStateDto4 = new OrderIndexStateDto();
                    indexStateDto4.setOrderID(stateDto.getOrderID().toString());
                    indexStateDto4.setStatus(5);
                    indexStateDto4.setPayTime(order5.getPayTime() + "");
                    indexStateDto4.setPayType(order5.getPayType());
                    indexStateDto4.setSendTime("0");
                    indexStateDto4.setFinishTime("0");
                    indexStateDto4.setSureTime(System.currentTimeMillis() + "");
                    indexStateDto4.setPayNO(order5.getPayNo());

                    stateDto.setState(5);
                    orderInfoMapper.updateStateByPrimaryKey(stateDto);
                    orderIndexService.updateState(indexStateDto4);

                    if (isOpenGoldPoint() && order5.getOrderPayType() != null && order5.getOrderPayType() == 1)
                        setPointV2(order5.getPayNo());
                    break;

                default:
                    throw new ServiceException("状态参数传入有误", RestConst.ErrorCode.FORM_FAIL);
            }
            //orderInfoMapper.updateStateByPrimaryKey(stateDto);
        } catch (Exception e) {
            e.printStackTrace();
            //throw new ServiceException("修改状态失败：", e);
        }
        return true;
    }


    /**
     * erp 订单撤销
     *
     * @param stateDto
     * @return
     */
    public synchronized boolean recallOrderErp(final OrderStateDto stateDto) {
        try {
            OrderInfo order5 = orderInfoMapper.selectByPrimaryKey(stateDto.getOrderID());

            verifyMD5(stateDto.getOrderID());  //验证MD5加密信息
            stateDto.setSureTime(CommonUtils.getCurTimestamp());

            OrderIndexStateDto indexStateDto4 = new OrderIndexStateDto();
            indexStateDto4.setOrderID(stateDto.getOrderID().toString());
            indexStateDto4.setStatus(5);
            indexStateDto4.setPayTime(order5.getPayTime() + "");
            indexStateDto4.setPayType(order5.getPayType());
            indexStateDto4.setSendTime("0");
            indexStateDto4.setFinishTime("0");
            indexStateDto4.setSureTime(System.currentTimeMillis() + "");
            indexStateDto4.setPayNO(order5.getPayNo());
            orderIndexService.updateState(indexStateDto4);
            stateDto.setState(5);
        } catch (Exception e) {
            throw new ServiceException("修改状态失败：" + e);

        }
        return true;
    }

    //添加物流运单号
    public String addLogistics(OrderLogistics orderLogistics) {
        OrderLogistics logistics = orderLogisticsMapper.selectByOrderID(orderLogistics.getOrderID());
        if (logistics != null) {
            orderLogisticsMapper.deleteByPrimaryKey(logistics.getId());
        }
        orderLogistics.setId(IdGen.get().nextId());
        orderLogistics.setAddTime(CommonUtils.getCurTimestamp());
        orderLogisticsMapper.insertSelective(orderLogistics);
        return "success";
    }

    //根据orderID查询物流运单信息
    public OrderLogistics selectLogisticByOrderID(Long orderID) {
        return orderLogisticsMapper.selectByOrderID(orderID);
    }

    //根据userID查询未付款及其未收货数量
    public Object selectTipsByUserID(Long userID) {
        Map<String, Integer> map = new HashMap<>();
        Object object = orderInfoMapper.selectTipsByUserID(userID);
        if (object == null) {
            map.put("unpaidQty", 0);
            map.put("unReceiptQty", 0);
        } else {
            map = (Map<String, Integer>) object;
        }
        return map;
    }

    //按条件查询结算记录表
    public List<OrderSettlement> selectSettlement(SettlementConditionDto settlement) {
        settlement.setCompanyID(SystemContext.getCompanyID());
        return orderSettlementMapper.selectByConditon(settlement);
    }

    //查询所有包含未结算资金的月份数据
    public Object getDataByState(String type) throws Exception {
        List<Map<String, Integer>> yearMonthList = orderSettlementMapper.selectDistinctByState(type, SystemContext.getCompanyID());
        if (yearMonthList.size() > 0) {
            List<SettlementCountMoreVo> countMoreVoList = new ArrayList<>();
            for (Map<String, Integer> map : yearMonthList) {
                SettlementCountMoreVo countMoreVo = new SettlementCountMoreVo();
                SettlementForCountDto countDto = new SettlementForCountDto();
                countDto.setYear(map.get("year").toString());
                countDto.setMonth(map.get("month").toString());
                countDto.setState("0");
                countDto.setType(type);
                SettlementCountVo countVo = (SettlementCountVo) selectSettlementCount(countDto);
                BeanUtils.copyProperties(countMoreVo, countVo);

                SettlementConditionDto orderSettlement = new SettlementConditionDto();
                orderSettlement.setYear(map.get("year").toString());
                orderSettlement.setMonth(map.get("month").toString());
                orderSettlement.setState("0");
                orderSettlement.setType(type);
                orderSettlement.setCompanyID(SystemContext.getCompanyID());
                List<OrderSettlement> orderSettlementList = orderSettlementMapper.selectByConditon(orderSettlement);
                countMoreVo.setOrderSettlementList(orderSettlementList);
                countMoreVoList.add(countMoreVo);
            }
            return countMoreVoList;
        } else {
            return null;
        }
    }

    //按年月状态查询结算统计数据
    public Object selectSettlementCount(SettlementForCountDto countDto) {
        SettlementCountVo settlementCountVo = new SettlementCountVo();
        countDto.setCompanyID(SystemContext.getCompanyID());
        Object object = orderSettlementMapper.selectSettlementCount(countDto);
        if (object != null) {
            settlementCountVo = (SettlementCountVo) object;
        }
        settlementCountVo.setYear(countDto.getYear());
        settlementCountVo.setMonth(countDto.getMonth());
        settlementCountVo.setTransactionsTotal(settlementCountVo.getTransactionsTotal() == null ? BigDecimal.ZERO : settlementCountVo.getTransactionsTotal());
        settlementCountVo.setCommissionTotal(settlementCountVo.getCommissionTotal() == null ? BigDecimal.ZERO : settlementCountVo.getCommissionTotal());
        settlementCountVo.setBeSettlement(settlementCountVo.getTransactionsTotal().subtract(settlementCountVo.getCommissionTotal()));
        return settlementCountVo;
    }

    //资金结算
    public String updateSettlementState(List<Long> settlementIDList) {
        Map params = new HashMap();
        params.put("addTime", CommonUtils.getCurTimestamp());
        params.put("settlementIDList", settlementIDList);
        orderSettlementMapper.updateState(params);
        return "success";
    }

    /**
     * @param id    供应商或者分行ID
     * @param year
     * @param month
     * @param type
     * @return
     */
    public List<OrderAndItem> selectOrderAndItemList(Long id, int year, int month, int type) {
        SettlementSelectDto selectDto = new SettlementSelectDto();
        switch (type) {
            case 1:
                selectDto.setSellerID(id);
                break;
            case 2:
                selectDto.setBranchID(id);
                break;
        }
        Map<String, Long> timeMap = getYearMonthTimeSamp(year, month);
        selectDto.setStartTime(timeMap.get("startTimeSamp")); //指定年月起始时间戳
        selectDto.setEndTime(timeMap.get("endTimeSamp")); //指定年月下月起始时间戳
        selectDto.setCompanyID(SystemContext.getCompanyID());
        return orderInfoMapper.selectOrderAndItemList(selectDto);
    }


    /**
     * @param id    供应商或者分行ID
     * @param year
     * @param month
     * @param type
     * @return
     */
    public PageInfo<OrderAndItem> selectOrderAndItemListPage(Long id, int year, int month, int type, int pageNo,
                                                             int pageSize) {
        SettlementSelectDto selectDto = new SettlementSelectDto();
        switch (type) {
            case 1:
                selectDto.setSellerID(id);
                break;
            case 2:
                selectDto.setBranchID(id);
                break;
        }
        Map<String, Long> timeMap = getYearMonthTimeSamp(year, month);
        selectDto.setStartTime(timeMap.get("startTimeSamp")); //指定年月起始时间戳
        selectDto.setEndTime(timeMap.get("endTimeSamp")); //指定年月下月起始时间戳
        PageHelper.startPage(pageNo, pageSize);
        selectDto.setCompanyID(SystemContext.getCompanyID());
        List<String> orderIdList = orderInfoMapper.selectOrderIdAndItemList(selectDto);
        PageInfo<String> page = new PageInfo<>(orderIdList);
        List<OrderAndItem> list = orderInfoMapper.selectOrderAndItemListPage(orderIdList);
        PageInfo<OrderAndItem> page1 = new PageInfo<>(list);
        page1.setPageNum(page.getPageNum());
        page1.setSize(page.getSize());
        page1.setStartRow(page.getStartRow());
        page1.setEndRow(page.getEndRow());
        page1.setTotal(page.getTotal());
        page1.setPages(page.getPages());
        page1.setFirstPage(page.getFirstPage());
        page1.setNextPage(page.getNextPage());
        page1.setLastPage(page.getLastPage());

        return page1;
    }

    //查询银行本部的订单详情列表
    public Object selectOrderItemListBySelf(String oID, int year, int month, int pageNo, int pageSize) {
        Map<String, Object> param = getNameLevelByOID(oID);
        int level = Integer.valueOf(param.get("level").toString());
        OrderItemSelfDto selfDto = new OrderItemSelfDto();
        Map<String, Long> timeMap = getYearMonthTimeSamp(year, month);
        selfDto.setStartTime(timeMap.get("startTimeSamp")); //指定年月起始时间戳
        selfDto.setEndTime(timeMap.get("endTimeSamp")); //指定年月下月起始时间戳
        switch (level) {
            case 1:
                selfDto.setBranchID("0");
                break;
            case 2:
                selfDto.setBranchID(oID);
                selfDto.setTwoLevelBranchID("0");
                break;
            case 3:
                selfDto.setTwoLevelBranchID(oID);
                selfDto.setSubbranchID("0");
                break;
            case 4:
                selfDto.setSubbranchID(oID);
                break;
        }

//        List<OrderAndItem> orderList = orderInfoMapper.selectOrderItemBySelf(selfDto);
        PageHelper.startPage(pageNo, pageSize);
        selfDto.setCompanyID(SystemContext.getCompanyID());
        List<OrderInfo> infoList = orderInfoMapper.selectOrderInfoBySelf(selfDto);
        List<OrderAndItem> orderList = new ArrayList<>();
        PageInfo<OrderInfo> page = new PageInfo(infoList);
        if (infoList != null && infoList.size() > 0) {
            for (OrderInfo order : infoList) {
                OrderAndItem orderAndItem = new OrderAndItem();
                List<OrderItem> itemList = orderItemMapper.selectOrderItemByOrderId(order.getOrderID());
                try {
                    BeanUtils.copyProperties(orderAndItem, order);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
                orderAndItem.setOrderItemList(itemList);
                orderList.add(orderAndItem);
            }
        }
        if (orderList.size() > 0) {
            List<Long> userIDList = new ArrayList<>();
            for (OrderAndItem orderAndItem : orderList) {
                userIDList.add(orderAndItem.getUserID());
            }
            Map<String, Object> mobileMap = new HashMap<>();
            if (userIDList.size() > 0) {
                mobileMap = getMobileByUserIDList(userIDList);
            }
            for (OrderAndItem orderAndItem : orderList) {
                orderAndItem.setUserName(mobileMap.get(orderAndItem.getUserID().toString()).toString());
            }
        }
        PageInfo<OrderAndItem> page1 = new PageInfo(orderList);
        page1.setPageNum(page.getPageNum());
        page1.setSize(page.getSize());
        page1.setStartRow(page.getStartRow());
        page1.setEndRow(page.getEndRow());
        page1.setTotal(page.getTotal());
        page1.setPages(page.getPages());
        page1.setFirstPage(page.getFirstPage());
        page1.setNextPage(page.getNextPage());
        page1.setLastPage(page.getLastPage());
        return page1;
    }


    //查询银行供应商、本部查询订单详情列表 包含夏季部门
    public Object selectOrderItemListBySpplier(String oID, int year, int month, int pageNo, int pageSize, Long
            supplierID) {
        Map<String, Object> param = getNameLevelByOID(oID);
        int level = Integer.valueOf(param.get("level").toString());
        OrderItemSelfDto selfDto = new OrderItemSelfDto();
        Map<String, Long> timeMap = getYearMonthTimeSamp(year, month);
        selfDto.setStartTime(timeMap.get("startTimeSamp")); //指定年月起始时间戳
        selfDto.setEndTime(timeMap.get("endTimeSamp")); //指定年月下月起始时间戳
        switch (level) {
            case 1:
                selfDto.setBranchID("0");
                break;
            case 2:
                selfDto.setBranchID(oID);
                break;
            case 3:
                selfDto.setTwoLevelBranchID(oID);
                break;
            case 4:
                selfDto.setSubbranchID(oID);
                break;
        }

//        List<OrderAndItem> orderList = orderInfoMapper.selectOrderItemBySelf(selfDto);
        PageHelper.startPage(pageNo, pageSize);
        selfDto.setCompanyID(SystemContext.getCompanyID());
        selfDto.setSupplierID(supplierID);
        List<OrderInfo> infoList = orderInfoMapper.selectOrderInfoBySelf(selfDto);
        List<OrderAndItem> orderList = new ArrayList<>();
        PageInfo<OrderInfo> page = new PageInfo(infoList);
        if (infoList != null && infoList.size() > 0) {
            for (OrderInfo order : infoList) {
                OrderAndItem orderAndItem = new OrderAndItem();
                List<OrderItem> itemList = orderItemMapper.selectOrderItemByOrderId(order.getOrderID());
                try {
                    BeanUtils.copyProperties(orderAndItem, order);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
                orderAndItem.setOrderItemList(itemList);
                orderList.add(orderAndItem);
            }
        }
        if (orderList.size() > 0) {
            List<Long> userIDList = new ArrayList<>();
            for (OrderAndItem orderAndItem : orderList) {
                userIDList.add(orderAndItem.getUserID());
            }
            Map<String, Object> mobileMap = new HashMap<>();
            if (userIDList.size() > 0) {
                mobileMap = getMobileByUserIDList(userIDList);
            }
            for (OrderAndItem orderAndItem : orderList) {
                orderAndItem.setUserName(mobileMap.get(orderAndItem.getUserID().toString()).toString());
            }
        }
        PageInfo<OrderAndItem> page1 = new PageInfo(orderList);
        page1.setPageNum(page.getPageNum());
        page1.setSize(page.getSize());
        page1.setStartRow(page.getStartRow());
        page1.setEndRow(page.getEndRow());
        page1.setTotal(page.getTotal());
        page1.setPages(page.getPages());
        page1.setFirstPage(page.getFirstPage());
        page1.setNextPage(page.getNextPage());
        page1.setLastPage(page.getLastPage());
        return page1;
    }

    public Object selectSupplierOrderItemListSelf(String oID, int year, int month, int pageNo, int pageSize, Long
            supplierID) {
        Map<String, Object> param = getNameLevelByOID(oID);
        int level = Integer.valueOf(param.get("level").toString());
        OrderItemSelfDto selfDto = new OrderItemSelfDto();
        Map<String, Long> timeMap = getYearMonthTimeSamp(year, month);
        selfDto.setStartTime(timeMap.get("startTimeSamp")); //指定年月起始时间戳
        selfDto.setEndTime(timeMap.get("endTimeSamp")); //指定年月下月起始时间戳
        switch (level) {
            case 1:
                selfDto.setBranchID("0");
                break;
            case 2:
                selfDto.setBranchID(oID);
                selfDto.setTwoLevelBranchID("0");
                break;
            case 3:
                selfDto.setTwoLevelBranchID(oID);
                selfDto.setSubbranchID("0");
                break;
            case 4:
                selfDto.setSubbranchID(oID);
                break;
        }

//        List<OrderAndItem> orderList = orderInfoMapper.selectOrderItemBySelf(selfDto);
        selfDto.setCompanyID(SystemContext.getCompanyID());
        selfDto.setSupplierID(supplierID);
        PageHelper.startPage(pageNo, pageSize);
        List<OrderInfo> infoList = orderInfoMapper.selectOrderInfoBySelf(selfDto);
        List<OrderAndItem> orderList = new ArrayList<>();
        PageInfo<OrderInfo> page = new PageInfo(infoList);
        if (infoList != null && infoList.size() > 0) {
            for (OrderInfo order : infoList) {
                OrderAndItem orderAndItem = new OrderAndItem();
                List<OrderItem> itemList = orderItemMapper.selectOrderItemByOrderId(order.getOrderID());
                try {
                    BeanUtils.copyProperties(orderAndItem, order);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
                orderAndItem.setOrderItemList(itemList);
                orderList.add(orderAndItem);
            }
        }
        if (orderList.size() > 0) {
            List<Long> userIDList = new ArrayList<>();
            for (OrderAndItem orderAndItem : orderList) {
                userIDList.add(orderAndItem.getUserID());
            }
            Map<String, Object> mobileMap = new HashMap<>();
            if (userIDList.size() > 0) {
                mobileMap = getMobileByUserIDList(userIDList);
            }
            for (OrderAndItem orderAndItem : orderList) {
                orderAndItem.setUserName(mobileMap.get(orderAndItem.getUserID().toString()).toString());
            }
        }
        PageInfo<OrderAndItem> page1 = new PageInfo(orderList);
        page1.setPageNum(page.getPageNum());
        page1.setSize(page.getSize());
        page1.setStartRow(page.getStartRow());
        page1.setEndRow(page.getEndRow());
        page1.setTotal(page.getTotal());
        page1.setPages(page.getPages());
        page1.setFirstPage(page.getFirstPage());
        page1.setNextPage(page.getNextPage());
        page1.setLastPage(page.getLastPage());
        return page1;
    }


    //按银行清单导出
    public Object getDetailList(String oID, int year, int month, Long supplierID) {
        Map<String, Object> param = getNameLevelByOID(oID);
        int level = Integer.valueOf(param.get("level").toString());
        OrderItemSelfDto selfDto = new OrderItemSelfDto();
        Map<String, Long> timeMap = getYearMonthTimeSamp(year, month);
        selfDto.setStartTime(timeMap.get("startTimeSamp")); //指定年月起始时间戳
        selfDto.setEndTime(timeMap.get("endTimeSamp")); //指定年月下月起始时间戳
        switch (level) {
            case 1:
                selfDto.setBranchID("0");
                break;
            case 2:
                selfDto.setBranchID(oID);
                break;
            case 3:
                selfDto.setTwoLevelBranchID(oID);
                break;
            case 4:
                selfDto.setSubbranchID(oID);
                break;
        }
        selfDto.setSupplierID(supplierID);
        selfDto.setCompanyID(SystemContext.getCompanyID());
        List<DetailListVo> detailListVoList = orderInfoMapper.selectDetailList(selfDto);
        List<Long> branchIDList = new ArrayList<>();
        List<Long> twoLevelBranchIDList = new ArrayList<>();
        List<Long> subbranchIDList = new ArrayList<>();
        List<Long> userIDList = new ArrayList<>();
        if (detailListVoList.size() > 0) {
            for (DetailListVo detailListVo : detailListVoList) {
                userIDList.add(detailListVo.getUserID());
                if (!branchIDList.contains(detailListVo.getBranchID())) {
                    branchIDList.add(detailListVo.getBranchID());
                }
                if (!twoLevelBranchIDList.contains(detailListVo.getTwoLevelBranchID())) {
                    twoLevelBranchIDList.add(detailListVo.getTwoLevelBranchID());
                }
                if (!subbranchIDList.contains(detailListVo.getSubbranchID())) {
                    subbranchIDList.add(detailListVo.getSubbranchID());
                }
            }
        }
        Map<String, Object> mobileMap = new HashMap<>();
        if (userIDList.size() > 0) {
            mobileMap = getMobileByUserIDList(userIDList);
        }

        Map<String, Object> branchMap = new HashMap<>();
        Map<String, Object> twoLevelBranchMap = new HashMap<>();
        Map<String, Object> subbranchMap = new HashMap<>();
        if (branchIDList.size() > 0) {
            branchMap = getBranchMap(branchIDList);
        }
        if (twoLevelBranchIDList.size() > 0) {
            twoLevelBranchMap = getBranchMap(twoLevelBranchIDList);
        }
        if (subbranchIDList.size() > 0) {
            subbranchMap = getBranchMap(subbranchIDList);
        }
        if (detailListVoList.size() > 0) {
            for (DetailListVo detailListVo : detailListVoList) {
                detailListVo.setUserName(mobileMap.get(detailListVo.getUserID().toString()).toString());
                if (detailListVo.getBranchID() == 0) {
                    detailListVo.setBranchName("总部本部");
                } else {
                    detailListVo.setBranchName(branchMap.get(detailListVo.getBranchID().toString()).toString());
                }

                if (detailListVo.getTwoLevelBranchID() == 0) {
                    if (detailListVo.getBranchID() != 0) {
                        detailListVo.setTwoLevelBranchName("本部");
                    }
                } else {
                    detailListVo.setTwoLevelBranchName(twoLevelBranchMap.get(detailListVo.getTwoLevelBranchID().toString()).toString());
                }

                if (detailListVo.getSubbranchID() == 0) {
                    if (detailListVo.getTwoLevelBranchID() != 0) {
                        detailListVo.setSubbranchName("本部");
                    }
                } else {
                    detailListVo.setSubbranchName(subbranchMap.get(detailListVo.getSubbranchID().toString()).toString());
                }
            }
        }
        return detailListVoList;
    }

    public Object getDetailListSelf(String oID, int year, int month, Long supplierID) {
        Map<String, Object> param = getNameLevelByOID(oID);
        int level = Integer.valueOf(param.get("level").toString());
        OrderItemSelfDto selfDto = new OrderItemSelfDto();
        Map<String, Long> timeMap = getYearMonthTimeSamp(year, month);
        selfDto.setStartTime(timeMap.get("startTimeSamp")); //指定年月起始时间戳
        selfDto.setEndTime(timeMap.get("endTimeSamp")); //指定年月下月起始时间戳
        switch (level) {
            case 1:
                selfDto.setBranchID("0");
                break;
            case 2:
                selfDto.setBranchID(oID);
                selfDto.setTwoLevelBranchID("0");
                break;
            case 3:
                selfDto.setTwoLevelBranchID(oID);
                selfDto.setSubbranchID("0");
                break;
            case 4:
                selfDto.setSubbranchID(oID);
                break;
        }
        selfDto.setSupplierID(supplierID);
        selfDto.setCompanyID(SystemContext.getCompanyID());
        List<DetailListVo> detailListVoList = orderInfoMapper.selectDetailList(selfDto);
        List<Long> branchIDList = new ArrayList<>();
        List<Long> twoLevelBranchIDList = new ArrayList<>();
        List<Long> subbranchIDList = new ArrayList<>();
        List<Long> userIDList = new ArrayList<>();
        if (detailListVoList.size() > 0) {
            for (DetailListVo detailListVo : detailListVoList) {
                userIDList.add(detailListVo.getUserID());
                if (!branchIDList.contains(detailListVo.getBranchID())) {
                    branchIDList.add(detailListVo.getBranchID());
                }
                if (!twoLevelBranchIDList.contains(detailListVo.getTwoLevelBranchID())) {
                    twoLevelBranchIDList.add(detailListVo.getTwoLevelBranchID());
                }
                if (!subbranchIDList.contains(detailListVo.getSubbranchID())) {
                    subbranchIDList.add(detailListVo.getSubbranchID());
                }
            }
        }
        Map<String, Object> mobileMap = new HashMap<>();
        if (userIDList.size() > 0) {
            mobileMap = getMobileByUserIDList(userIDList);
        }

        Map<String, Object> branchMap = new HashMap<>();
        Map<String, Object> twoLevelBranchMap = new HashMap<>();
        Map<String, Object> subbranchMap = new HashMap<>();
        if (branchIDList.size() > 0) {
            branchMap = getBranchMap(branchIDList);
        }
        if (twoLevelBranchIDList.size() > 0) {
            twoLevelBranchMap = getBranchMap(twoLevelBranchIDList);
        }
        if (subbranchIDList.size() > 0) {
            subbranchMap = getBranchMap(subbranchIDList);
        }
        if (detailListVoList.size() > 0) {
            for (DetailListVo detailListVo : detailListVoList) {
                detailListVo.setUserName(mobileMap.get(detailListVo.getUserID().toString()).toString());
                if (detailListVo.getBranchID() == 0) {
                    detailListVo.setBranchName("总部本部");
                } else {
                    detailListVo.setBranchName(branchMap.get(detailListVo.getBranchID().toString()).toString());
                }

                if (detailListVo.getTwoLevelBranchID() == 0) {
                    if (detailListVo.getBranchID() != 0) {
                        detailListVo.setTwoLevelBranchName("本部");
                    }
                } else {
                    detailListVo.setTwoLevelBranchName(twoLevelBranchMap.get(detailListVo.getTwoLevelBranchID().toString()).toString());
                }

                if (detailListVo.getSubbranchID() == 0) {
                    if (detailListVo.getTwoLevelBranchID() != 0) {
                        detailListVo.setSubbranchName("本部");
                    }
                } else {
                    detailListVo.setSubbranchName(subbranchMap.get(detailListVo.getSubbranchID().toString()).toString());
                }
            }
        }
        return detailListVoList;
    }

    /**
     * 导出对账报表
     *
     * @param exportDto
     * @return
     */
    public Object OrderDetailForExport(OrderExportDto exportDto) {
        exportDto.setDatabaseTable(databaseTableUser);
        exportDto.setCompanyID(SystemContext.getCompanyID());
        List<OrderAndItem> orderAndItemList = orderInfoMapper.orderDetailForExport(exportDto);
        return orderAndItemList;
    }

    //供应商首页统计数据打包
    public Object selectHomepageCount(Long sellerID) {
        //订单统计数据
        OrderCountDto countDto = new OrderCountDto();
        countDto.setSellerID(sellerID);
        OrderCountVo countVo = selectOrderCount(countDto);
        //已结算、未结算资金
        countVo.setSettlementTotal(selectSettlementTotal(sellerID) == null ? BigDecimal.ZERO : selectSettlementTotal(sellerID));
        countVo.setNotSettlementTotal(countVo.getTransactionTotal().subtract(countVo.getSettlementTotal()));

        //供应商交易提示
        SupplierTradingTipsVo tipsVo = selectSupplierTradingTips(sellerID);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("goodsCount", goodsService.queryGoodsCountData(sellerID, 1)); //商品统计
        resultMap.put("orderCount", countVo);
        resultMap.put("supplierTradingTips", tipsVo);
        return resultMap;
    }

    //供应商首页统计数据打包V2
    public Object selectHomepageCountV2(Long sellerID) {
        //订单统计数据
        OrderCountDto countDto = new OrderCountDto();
        countDto.setSellerID(sellerID);
        OrderCountVo countVo = selectOrderCountV2(countDto);

        //供应商交易提示
        SupplierTradingTipsVo tipsVo = selectSupplierTradingTips(sellerID);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("goodsCount", goodsService.queryGoodsCountData(sellerID, 1)); //商品统计
        resultMap.put("orderCount", countVo);
        resultMap.put("supplierTradingTips", tipsVo);
        return resultMap;
    }

    //供应商商品订单数，商品销售额，排序
    public PageInfo selectGoodsSalesMore(int pageNum, int pageSize, Map<String, Object> param) {
        PageHelper.startPage(pageNum, pageSize);
        param.put("companyID", SystemContext.getCompanyID());
        List<Map<String, Object>> qtyAndSalesList = orderItemMapper.selectGoodsSalesMore(param);
        PageInfo<Map<String, Object>> page = new PageInfo(qtyAndSalesList);
        return page;
    }

    //定时任务（订单未付款超过1小时则失效,每天临时开始）
    public Object timeTaskOrderCancel() {
        OrderSelectDto selectDto = new OrderSelectDto();
        selectDto.setState(1);
        List<OrderInfo> orderInfoList = orderInfoMapper.selectListByConditon(selectDto); //1待付款
        if (orderInfoList.size() > 0) {
            for (OrderInfo oi : orderInfoList) {
                if (CommonUtils.getCurTimestamp() - oi.getAddTime() > 3600000) {
                    OrderStateDto stateDto = new OrderStateDto();
                    stateDto.setOrderID(oi.getOrderID());
                    stateDto.setState(0);
                    updateState2(stateDto);  //超过20小时未付款的订单则取消

                    if (oi.getPointQty() != null && oi.getPointQty().compareTo(BigDecimal.ZERO) == 1) {
                        BackPointDto backPointDto = new BackPointDto(oi.getUserID() + "", oi.getPointQty(), oi.getOrderID() + "", "");
//                    JSONArray.fromObject(backPointDto).toString();
                        JSONObject jsonObject = HttpUtil.httpPOSTJSONObject(ProConstants.getReturnPoint, backPointDto, restTemplate, true);
                        //if (jsonObject.get("isSuccess") != 1) {
                        if (!com.google.common.base.Objects.equal(DataUtils.getInteger(jsonObject, "isSuccess"), 1)) {
                            logger.error("返回订单失效" + oi.getPayNo());
                        }
                    }

                }
            }
        }
        return "success";
    }


//    public Object testBackPoint(){
//        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(864471788640276480l);
//        if(orderInfo.getPointQty()!=null){
//            BackPointDto backPointDto = new BackPointDto(orderInfo.getUserID()+"",orderInfo.getPointQty(),orderInfo.getOrderID()+"","");
////                    JSONArray.fromObject(backPointDto).toString();
//            JSONObject jsonObject = HttpUtil.httpPost(ProConstants.getReturnPoint,backPointDto, JSONObject.class);
//            if (jsonObject.get("isSuccess") != 1) {
//                throw new ServiceException("返还订单中的金豆失败,订单号:"+orderInfo.getOrderID(), RestConst.ErrorCode.SERVICE_FAIL);
//            }
//        }
//        return 1;
//    }

    /**
     * 定时任务，生成上月结算记录(银行结算，供应商结算)
     * TODO 中收结账
     *
     * @param year  不传值则统计上月
     * @param month 不传值则统计上月
     * @return
     */
    public Object timetaskSettlement(Integer year, Integer month) {
        //清空start
        if (year != null && month != null) {
            //orderSettlementMapper.deleteByMonthRecord(year,month);
            orderBankSettlementMapper.deleteByMonthRecord(year, month);
        }
        //清空end

        Long startTime;
        Long endTime;
        if (year == null || month == null) {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.MONTH, -1);
            year = cal.get(Calendar.YEAR);
            month = cal.get(Calendar.MONTH) + 1;
            startTime = getTimeSamp(1); //上月起始时间戳
            endTime = getTimeSamp(2);  //本月起始时间戳
        } else {
            Map<String, Long> timeMap = getYearMonthTimeSamp(year, month);
            startTime = timeMap.get("startTimeSamp"); //指定月起始时间戳
            endTime = timeMap.get("endTimeSamp");  //指定月下月起始时间戳
        }

        Map<String, Object> param = new HashMap<>();
        param.put("year", year);
        param.put("month", month);
       /* List<OrderSettlement> settlementListO = orderSettlementMapper.selectByYearMonth(param);
        if (settlementListO.size() > 0) {
            throw new ServiceException("该月资金结算记录已生成", RestConst.ErrorCode.SERVICE_FAIL);
        }*/

        SettlementSelectDto selectDto = new SettlementSelectDto();
        selectDto.setStartTime(startTime);
        selectDto.setEndTime(endTime);
        selectDto.setCompanyID(null);
        //List<OrderSettlement> settlementList = orderInfoMapper.selectSettlement(selectDto);//附加了companyID
        List<OrderBankSettlement> bankSettlementList = orderInfoMapper.selectBranchBankSettle(selectDto);//附加了companyID

        Long curTimeStamp = CommonUtils.getCurTimestamp();
       /* for (OrderSettlement settlement : settlementList) {
            settlement.setId(IdGen.get().nextId());
            settlement.setAddTime(curTimeStamp);
            settlement.setState(0);
            settlement.setType(1);
            settlement.setYear(year);
            settlement.setMonth(month);
        }*/
        for (OrderBankSettlement bankSettlement : bankSettlementList) {
            bankSettlement.setId(IdGen.get().nextId());
            bankSettlement.setAddTime(curTimeStamp);
            bankSettlement.setState(0);
            bankSettlement.setYear(year);
            bankSettlement.setMonth(month);
        }
       /* if (settlementList.size() > 0) {
            orderSettlementMapper.insertBatch(settlementList);
        }*/
        if (bankSettlementList.size() > 0) {
            orderBankSettlementMapper.insertBatch(bankSettlementList);
        }
        return "success";
    }

    //定时任务，发货后超过7天时间则自动确认收货
    public Object timetaskOrderReceipt() {
        OrderSelectDto selectDto = new OrderSelectDto();
        selectDto.setState(3);
        List<OrderInfo> orderInfoList = orderInfoMapper.selectListByConditon(selectDto); //已发货
        if (orderInfoList.size() > 0) {
            for (OrderInfo orderInfo : orderInfoList) {
                if (CommonUtils.getCurTimestamp() - orderInfo.getSendTime() > 604800000) {  //超过10天
                    OrderStateDto stateDto = new OrderStateDto();
                    stateDto.setOrderID(orderInfo.getOrderID());
                    stateDto.setState(4);   //已完成
                    updateState2(stateDto);
                    try {
                        if (isOpenErp()) {
                            //getConfirmSendOrder == getSecretKey
                            ResultData resultData = OrderController.httpGet(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.CONFIRMSENDORDER.getCode()) + "?orderNO=" + orderInfo.getOrderID(), CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SECRETKEY.getCode()));
                            if (!Objects.equal("1", resultData.getCode())) {
                                logger.info("定时任务7天确认收货同步失败orderID ===" + orderInfo.getOrderID());
                                // throw new ServiceException("收货失败");
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.info("定时任务7天确认收货同步失败orderID == " + orderInfo.getOrderID());
                    } catch (Error e) {
                        e.printStackTrace();
                        logger.info("定时任务7天确认收货同步失败orderID == " + orderInfo.getOrderID());
                    }
                }
            }
        }
        return "success";
    }

    //定时任务：已生成支付单号，但未付款的单据及其金额
    public Object getUnpaidPayOrder(Long startTime, Long endTime) {
        if (startTime == null || endTime == null) {
            startTime = getTimeSampDay(1);
            endTime = getTimeSampDay(2);
        }
        List<String> resultList = orderInfoMapper.selectPayNoByNopaind(startTime, endTime);
        return resultList;
    }

    /**
     * 供应商中收结算 按月结算
     *
     * @param year  不传则统计上月
     * @param month 不传则统计上月
     * @return
     */
    public Object timetaskSupplierSettlementByMonth(Integer year, Integer month) {
        Long startTime;
        Long endTime;
        if (year == null || month == null) {
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.MONTH, -1);
            startTime = getTimeSamp(1); //上月起始时间戳
            endTime = getTimeMillisSamp(1);  //上月结束时间戳
        } else {
            Map<String, Long> timeMap = getYearMonthTimeMillisSamp(year, month);
            startTime = timeMap.get("startTimeSamp"); //指定月起始时间戳
            endTime = timeMap.get("endTimeSamp");  //指定月结束时间戳
        }
        return timetaskSupplierSettlement(startTime, endTime, 2);
    }

    /**
     * 供应商中收结算 按月结算
     *
     * @param date 不传则按当天(t+7)计算
     * @return
     */
    public Object timetaskSupplierSettlementByDay(Integer year, Integer month, Integer date) {
        Long startTime, endTime;
        if (null == year || null == month || null == date) {
            //默认当前日期 t+7
            Calendar cal = Calendar.getInstance();
            year = cal.get(Calendar.YEAR);
            month = cal.get(Calendar.MONTH);
            date = cal.get(Calendar.DAY_OF_MONTH) - 7;
        } else {
            month = month - 1;
        }

        Map<String, Long> timeMap = getDayBeginEndTimeSamp(year, month, date);
        startTime = timeMap.get("startTimeSamp");
        endTime = timeMap.get("endTimeSamp");
        System.out.println(startTime);
        System.out.println(endTime);
        return timetaskSupplierSettlement(startTime, endTime, 1);
    }

    /**
     * 供应商中收结算
     *
     * @param startTime
     * @param endTime
     * @param type      1：t+7 2:月结
     * @return
     */
    public Object timetaskSupplierSettlement(Long startTime, Long endTime, Integer type) {
        Map<String, Object> param = new HashMap<>();
        param.put("beginTime", startTime);
        param.put("endTime", endTime);
        param.put("companyID", SystemContext.getCompanyID());
        List<OrderSupplierSettlement> supplierSettlementListO = orderSupplierSettlementMapper.selectByBeginAndEndTime(param);
        if (supplierSettlementListO.size() > 0) {
            throw new ServiceException("该月供应商中收结算记录已生成", RestConst.ErrorCode.SERVICE_FAIL);
        }

        SupplierSettlementSelectDto selectDto = new SupplierSettlementSelectDto();
        selectDto.setSettleType(type);
        selectDto.setBeginTime(startTime);
        selectDto.setEndTime(endTime);
        selectDto.setCompanyID(null);
        selectDto.setDatabaseTable(databaseTableUser);
        selectDto.setCompanyID(SystemContext.getCompanyID());
        List<OrderSupplierSettlement> supplierSettlementList = orderInfoMapper.selectSupplierSettlement(selectDto);//附加了companyID

        Long curTimeStamp = CommonUtils.getCurTimestamp();
        for (OrderSupplierSettlement settlement : supplierSettlementList) {
            settlement.setId(IdGen.get().nextId());
            settlement.setAddTime(curTimeStamp);
            settlement.setState(0);
            settlement.setType(type);
            settlement.setBeginTime(startTime);
            settlement.setEndTime(endTime);
        }
        if (supplierSettlementList.size() > 0) {
            orderSupplierSettlementMapper.insertBatch(supplierSettlementList);
        }
        return "success";
    }

    /**
     * 初始化供应商对账单
     *
     * @param start 开始日期
     * @param end   结束日期
     * @return
     */
    public Object supplierSettlementByDay(String start, String end) {
        try {
            Long startDate = new SimpleDateFormat("yy-MM-dd").parse(start).getTime();
            Long endDate = new SimpleDateFormat("yy-MM-dd").parse(end).getTime();
            for (Long i = startDate; i <= endDate; i = i + 24 * 3600 * 1000) {
                Date date = new Date(i);
                Integer year = Integer.valueOf(new SimpleDateFormat("yyyy").format(date));
                Integer month = Integer.valueOf(new SimpleDateFormat("MM").format(date));
                Integer day = Integer.valueOf(new SimpleDateFormat("dd").format(date));
                timetaskSupplierSettlementByDay(year, month, day);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }


    /**
     * 供应商中收明细
     *
     * @param conditionDto
     * @return
     */
    public Object supplierSettlementConditionDto(SupplierSettlementConditionDto conditionDto) {
        Map<String, Object> map = new HashMap();//返回结果的map
       /* if(null==conditionDto.getYear()||conditionDto.getYear()==0){
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.MONTH, -1);
            conditionDto.setYear(cal.get(Calendar.YEAR));
        }

        Map<String, Long> timeMap = getYearStartEndTimeSamp(conditionDto.getYear());
        conditionDto.setBeginTime(timeMap.get("startTimeSamp"));
        conditionDto.setEndTime(timeMap.get("endTimeSamp"));*/
        conditionDto.setCompanyID(SystemContext.getCompanyID());
        Map settlementTotal = orderSupplierSettlementMapper.supplierSettlementTotal(conditionDto);

        //设置分页处理
        PageHelper.startPage(conditionDto.getPageNum(), conditionDto.getPageSize());
        List<OrderSupplierSettlement> orderSupplierSettlements = orderSupplierSettlementMapper.selectByCondition(conditionDto);
        PageInfo page = new PageInfo(orderSupplierSettlements);

        map.put("settlementTotal", settlementTotal);
        map.put("list", page);
        map.put("pageCounts", page.getTotal());
        return map;
    }

    /**
     * 供应商中收按天明细
     *
     * @param selectDto
     * @return
     */
    public Object supplierSettlementDetail(SupplierSettlementSelectDetailDto selectDto) {
        Map<String, Object> map = new HashMap();//返回结果的map
        selectDto.setCompanyID(SystemContext.getCompanyID());
        List<Map<String, Object>> settlementsDetail = orderInfoMapper.supplierSettlementGroupByDate(selectDto);

        map.put("list", settlementsDetail);
        return map;
    }


    /**
     * 供应商中收订单详情
     *
     * @param selectDto
     * @return
     */
    public Object supplierSettlementOrderInfo(SupplierSettlementSelectDetailDto selectDto) {
        Map<String, Object> map = new HashMap();//返回结果的map

        selectDto.setCompanyID(SystemContext.getCompanyID());

        Map settlementTotal = orderInfoMapper.supplierSettlementOrderTotal(selectDto);

        //设置分页处理
        PageHelper.startPage(selectDto.getPageNum(), selectDto.getPageSize());
        List<SupplierSettlementOrderDto> settlementsOrderInfoList = orderInfoMapper.supplierSettlementOrderInfo(selectDto);
        PageInfo page = new PageInfo(settlementsOrderInfoList);

        settlementTotal.put("beginTime", selectDto.getBeginTime());
        settlementTotal.put("endTime", selectDto.getEndTime());
        map.put("settlementTotal", settlementTotal);
        map.put("list", page);
        map.put("pageCounts", page.getTotal());

        return map;
    }

    //中收结算
    public String updateSupplierSettlementState(List<Long> supplierSettlementState) {
        Map params = new HashMap();
        params.put("settleTime", CommonUtils.getCurTimestamp());
        params.put("supplierSettlementIDList", supplierSettlementState);
        orderSupplierSettlementMapper.updateState(params);
        return "success";
    }


    //插入订单明细快照表
    private void insertSnapshot(Long itemID, Long companyID) {
        OrderItem orderItem1 = orderItemMapper.selectByPrimaryKey(itemID);
        orderItem1.setMemo(null);
        String itemJson = JSONArray.fromObject(orderItem1).toString();
        OrderSnapshot orderSnapshot = new OrderSnapshot();
        orderSnapshot.setID(IdGen.get().nextId());
        orderSnapshot.setItemID(orderItem1.getItemID());
        orderSnapshot.setJson(itemJson);
        orderSnapshot.setCompanyID(companyID);
        orderSnapshotMapper.insertSelective(orderSnapshot);
    }

    //修改订单明细快照表
    private void updateSnapshot(Long itemID, Long companyID) {
        OrderItem orderItem1 = orderItemMapper.selectByPrimaryKey(itemID);
        orderItem1.setMemo(null);
        String itemJson = JSONArray.fromObject(orderItem1).toString();
        OrderSnapshot orderSnapshot = new OrderSnapshot();
        //orderSnapshot.setID(IdGen.get().nextId());
        //orderSnapshot.setItemID(orderItem1.getItemID());
        orderSnapshot.setJson(itemJson);
        //orderSnapshot.setCompanyID(companyID);
        orderSnapshotMapper.updateByPrimaryKey(orderSnapshot);
    }

    //获取下订单需要的UserInfo及其组织信息
    private Object getUserInfoForOrder(Long userID) {
        JSONObject jsonObject = HttpUtil.httpGetJSONObject(ProConstants.getUserInfoForOrder + userID, restTemplate);
        if (!com.google.common.base.Objects.equal(DataUtils.getInteger(jsonObject, "isSuccess"), 1)) {
            throw new ServiceException("用户信息有误", RestConst.ErrorCode.SERVICE_FAIL);
        }
        return (UserInfoForOrderDto) JSONObject.toBean(jsonObject.getJSONObject("data"), UserInfoForOrderDto.class);
    }

    /**
     * 获取会员价开关
     *
     * @param companyID
     * @return
     */
    private Long getVipPriceSW(Long companyID) {
        DataResult result = HttpUtil.httpGet(
                ProConstants.getVipPriceSW + companyID, restTemplate);
        return result.getIsSuccess() == 1 ? Long.valueOf(result.getData().toString()) : 0l;
    }


    //获取供应商交易提示
    private SupplierTradingTipsVo selectSupplierTradingTips(Long sellerID) {
        SupplierTradingTipsVo tipsVo = new SupplierTradingTipsVo();
        Object object = orderInfoMapper.selectSupplierTradingTips(sellerID);
        if (object == null) {
            tipsVo.setCompletedQty(0);
            tipsVo.setNotshippedQty(0);
            tipsVo.setNotSureReceiptQty(0);
            tipsVo.setSupplierSure(0);
            tipsVo.setUnpaidQty(0);
        } else {
            tipsVo = (SupplierTradingTipsVo) object;
        }
        return tipsVo;
    }

    //获取已结算金额统计（sellerID=null则是查询所有）
    public BigDecimal selectSettlementTotal(Long sellerID) {
        return orderSettlementMapper.settlementTotal(sellerID, SystemContext.getCompanyID());
    }

    //获取银行已结算扣点金额（branchID=null则是查询所有）
    public BigDecimal selectCommission(Long branchID) {
        return orderSettlementMapper.selectTotalCommission(branchID, SystemContext.getCompanyID());
    }

    //获取银行扣点总金额(branchID=null则查询所有)
    public BigDecimal selectTotalCommission(Long branchID) {
        return orderInfoMapper.selectTotalCommission(branchID, SystemContext.getCompanyID());
    }

    //获取银行扣点总金额(branchID=null则查询所有)
    public BigDecimal selectTotalEmployeeCommission(Long branchID) {
        return orderInfoMapper.selectTotalEmployeeCommission(branchID, SystemContext.getCompanyID());
    }

    /**
     * 按条件查询订单统计数据
     *
     * @param countDto
     * @return
     */
    public OrderCountVo selectOrderCount(OrderCountDto countDto) {
        countDto.setCompanyID(SystemContext.getCompanyID());
        OrderCountVo orderCountVo = orderInfoMapper.selectOrderCount(countDto);
        orderCountVo.setTransactionTotal(orderCountVo.getTransactionTotal() == null ? BigDecimal.ZERO : orderCountVo.getTransactionTotal());
        return orderCountVo;
    }

    public OrderCountVo selectOrderCountV2(OrderCountDto countDto) {
        countDto.setCompanyID(SystemContext.getCompanyID());
        OrderCountVo orderCountVo = orderInfoMapper.selectOrderCount(countDto);
        orderCountVo.setSalesTotal(orderCountVo.getSalesTotal() == null ? BigDecimal.ZERO : orderCountVo.getSalesTotal());
        return orderCountVo;
    }

    //一键建立所有订单索引
    public Object addAllIndex() {
        List<Long> orderIDList = orderInfoMapper.selectAllID();
        orderIndexService.addIndex(orderIDList, null);
        return "success";
    }

    //一键建立所有订单索引payNo
    public Object addPayNoIndex() {
        List<Long> orderIDList = orderInfoMapper.selectAllID();
        orderIndexService.addPayNoIndex(orderIDList);
        return "success";
    }

    //一键建立所有订单索引payNo
    public Object addPayNoIndexTest() {
        List<Long> orderIDList = orderInfoMapper.selectAllID();
        orderIndexService.updateIndexTest(orderIDList);
        return "success";
    }

    //一键建立所有订单索引payNo
    public Object addOrderIndexCompanyID() {
        List<Long> orderIDList = orderInfoMapper.selectAllID();
        orderIndexService.updateIndexCompanyID(orderIDList);
        return "success";
    }

    /**
     * 验证订单加密信息
     *
     * @param orderID
     */
    private void verifyMD5(Long orderID) {
        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderID);
        String md5 = CommonUtils.MD5(getAmountForMD5(orderInfo.getAmount().toString()) + orderInfo.getqty() + ProConstants.salt);
        if (!orderInfo.getMd5().equals(md5)) {
            throw new ServiceException("订单价格或订单商品数量有误，请联系管理员", RestConst.ErrorCode.DATABASE_ERROR);
        }

        List<OrderItem> itemList = orderItemMapper.selectByOrderID(orderID);
        for (OrderItem item : itemList) {
            String md51 = CommonUtils.MD5(getAmountForMD5(item.getAmount().toString()) + item.getQty() + ProConstants.salt);
            if (!item.getMd5().equals(md51)) {
                throw new ServiceException("订单价格或单商品数量有误，请联系管理员", RestConst.ErrorCode.DATABASE_ERROR);
            }
        }
    }

    /**
     * 获取当前年月起始时间戳
     *
     * @param state 1上月起始时间戳，2本月起始时间戳
     * @return
     */
    private Long getTimeSamp(int state) {
        Calendar cal = Calendar.getInstance();
        if (state == 1) {
            cal.add(Calendar.MONTH, -1);
        }
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
        cal.set(Calendar.MILLISECOND, 0);

        Long timeSamp = cal.getTimeInMillis();
        return timeSamp;
    }

    /**
     * 获取指定年月起始时间戳
     */
    private Map<String, Long> getYearMonthTimeSamp(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month - 1, 1);
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
        cal.set(Calendar.MILLISECOND, 0);

        Long startTimeSamp = cal.getTimeInMillis();
        cal.add(Calendar.MONTH, +1);
        Long endTimeSamp = cal.getTimeInMillis();

        Map<String, Long> params = new HashMap<>();
        params.put("startTimeSamp", startTimeSamp);
        params.put("endTimeSamp", endTimeSamp);
        return params;
    }

    /**
     * 获取需要的时间戳
     *
     * @param type 1昨天零点 2今天零点
     * @return
     */
    private Long getTimeSampDay(int type) {

        Calendar cal = Calendar.getInstance();
        if (type == 1) {
            cal.add(Calendar.DATE, -1);
        }
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTimeInMillis();
    }

    //去掉小数点后的0
    private String getAmountForMD5(String amount) {
        if (amount.indexOf(".") > 0) {
            amount = amount.replaceAll("0+?$", "");//去掉多余的0
            amount = amount.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return amount;
    }


    /**
     * lmn
     * 获取当前年月结束时间戳
     *
     * @param state 1上月结束时间戳，2本月结束时间戳
     * @return
     */
    private Long getTimeMillisSamp(int state) {
        Calendar cal = Calendar.getInstance();
        if (state == 1) {
            cal.add(Calendar.MONTH, -1);
        }
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
        cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 0);

        Long timeSamp = cal.getTimeInMillis();
        return timeSamp;
    }

    /**
     * lmn
     * 获取指定年月起始时间戳
     */
    private Map<String, Long> getYearMonthTimeMillisSamp(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month - 1, 1);
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
        cal.set(Calendar.MILLISECOND, 0);

        Long startTimeSamp = cal.getTimeInMillis();
        cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));

        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 0);
        Long endTimeSamp = cal.getTimeInMillis();

        Map<String, Long> params = new HashMap<>();
        params.put("startTimeSamp", startTimeSamp);
        params.put("endTimeSamp", endTimeSamp);
        return params;
    }


    /**
     * lmn
     * 获取指定年起始时间戳
     */
    private Map<String, Long> getYearStartEndTimeSamp(int year) {
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), 1, cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
        cal.set(Calendar.MILLISECOND, 0);

        Long startTimeSamp = cal.getTimeInMillis();
        cal.set(Calendar.MONTH, cal.getActualMaximum(Calendar.MONTH));
        cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));

        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 0);
        Long endTimeSamp = cal.getTimeInMillis();

        Map<String, Long> params = new HashMap<>();
        params.put("startTimeSamp", startTimeSamp);
        params.put("endTimeSamp", endTimeSamp);
        return params;
    }

    /**
     * @param date
     * @return
     */
    private Map<String, Long> getDayBeginEndTimeSamp(Integer year, Integer month, Integer date) {

        Calendar cal = Calendar.getInstance();
        cal.set(year, month, date, 0, 0, 0);
        cal.set(Calendar.MILLISECOND, 0);

        Long startTimeSamp = cal.getTimeInMillis();

        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 0);
        Long endTimeSamp = cal.getTimeInMillis();

        Map<String, Long> params = new HashMap<>();
        params.put("startTimeSamp", startTimeSamp);
        params.put("endTimeSamp", endTimeSamp);
        return params;
    }

   /* public static void main(String[] args) {
        System.out.println(new OrderService().getAmountForMD5("0.01"));
    }*/

    private Map<String, String> getAddress(String addressID) {
        Map<String, String> map = new HashMap<>();
        String url = ProConstants.getAddress + addressID;
        DataResult result = HttpUtil.httpGet(url, restTemplate);
        if (result.getIsSuccess() == 1) {
            Map<String, Object> mapResult = (Map<String, Object>) result.getData();
            if (mapResult != null) {
                map.put("address", mapResult.get("address").toString());
                map.put("contacts", mapResult.get("contacts").toString());
                map.put("contactPhone", mapResult.get("contactPhone").toString());
            }
        } else {
            map.put("address", "未查到");
            map.put("contacts", "未查到");
            map.put("contactPhone", "未查到");
        }
        return map;
    }

    //这里是修改 取代上面的getAdress接口的 可能在以前的旧数据上存在一定的问题
    private Map<String, String> getAddressInfo(OrderInfo orderInfo) {
        Map<String, String> map = new HashMap<>();
        if (orderInfo != null) {
            map.put("address", orderInfo.getReceiverAddress());
            map.put("contacts", orderInfo.getReceiverName());
            map.put("contactPhone", orderInfo.getReceiverPhone());
        } else {
            map.put("address", "未查到");
            map.put("contacts", "未查到");
            map.put("contactPhone", "未查到");
        }
        return map;
    }

    //获取银行的名称和级别
    private Map<String, Object> getNameLevelByOID(String oID) {
        DataResult result = HttpUtil.httpGet(ProConstants.getNameLevelByOID + oID, restTemplate);
        if (result.getIsSuccess() == 0) {
            throw new ServiceException("调用base服务获取银行信息失败", RestConst.ErrorCode.SERVICE_FAIL);
        }
        return (Map<String, Object>) result.getData();
    }

    //获取oID对应的name的List
    private Map<String, Object> getBranchMap(List<Long> list) {
        DataResult result = HttpUtil.httpPost(ProConstants.getBranchListAllState, list, restTemplate);
        if (result.getIsSuccess() != 1) {
            throw new ServiceException("调用base服务查询银行信息失败", RestConst.ErrorCode.SERVICE_FAIL);
        }
        return (Map<String, Object>) result.getData();
    }

    private Map<String, Object> getMobileByUserIDList(List<Long> userIDList) {
        Map<String, Object> mobileMap = new HashMap<>();
        DataResult result = HttpUtil.httpPost(ProConstants.getMobileByUserIDList, userIDList, restTemplate);
        if (result.getIsSuccess() == 0) {
            throw new ServiceException("调用base服务获取用户手机号失败", RestConst.ErrorCode.SERVICE_FAIL);
        }
        return (Map<String, Object>) result.getData();
    }


    //付款完成生成金豆
    private Object setPoint(String payNO) {


        List<OrderInfo> infoList = orderInfoMapper.selectByPayNo(payNO);
        int dealQty = 0;
        BigDecimal dealAmount1 = BigDecimal.ZERO; //用于计算金豆
        BigDecimal dealAmount2 = BigDecimal.ZERO;  //用于计算佣金
        BigDecimal dealAmount3 = BigDecimal.ZERO;  //计算丝绸之路产品的佣金
        DealDto dealDto = null;

        BigDecimal offsetQty = BigDecimal.ZERO;  //抵扣金豆数量
        BigDecimal offsetAmount = BigDecimal.ZERO;  //抵扣金豆金额
        BigDecimal silkPrice = BigDecimal.ZERO;  //丝绸之路产品price

        for (OrderInfo orderInfo : infoList) {
            List<OrderItem> itemList = orderItemMapper.selectByOrderID(orderInfo.getOrderID());
            for (OrderItem orderItem : itemList) {
                if (getGoldenGoodsID().equals(orderItem.getGoodsID().toString())) {
                    dealQty += orderItem.getQty();
                    //计算丝绸之路产品的无佣金 2017-4-26
                    dealAmount3 = dealAmount3.add(orderItem.getAmount());
                    silkPrice = orderItem.getRetailPrice();
                    //dealAmount2 = dealAmount2.add(orderItem.getAmount());

                }
                GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(orderItem.getGoodsID());
                if (goodsInfo.getClassifyID().equals(getGoldenClassifyID())) {
                    dealAmount1 = dealAmount1.add(orderItem.getAmount());
                    dealAmount2 = dealAmount2.add(orderItem.getAmount());
                }
            }

            if (dealDto == null) {
                dealDto = new DealDto();
                dealDto.setSubbranchId(orderInfo.getSubbranchID());//支行ID
                dealDto.setBranchId(orderInfo.getBranchID());//分行ID
                dealDto.setTwoLevelBranchId(orderInfo.getTwoLevelBranchID());//二级分行ID
                dealDto.setManagerID(orderInfo.getSalesManagerID().toString());
                dealDto.setUserID(orderInfo.getUserID().toString());
                dealDto.setUserName(orderInfo.getUserName());

                //added companyid , by tim peng 2017-4-7
                UserInfoForOrderDto userInfoForOrderDto = (UserInfoForOrderDto) getUserInfoForOrder(orderInfo.getUserID());
                if (userInfoForOrderDto != null) {
                    dealDto.setCompanyID(userInfoForOrderDto.getCompanyID());
                }
            }


            if (orderInfo.getPointQty() != null) {
                offsetQty = orderInfo.getPointQty();
                offsetAmount = orderInfo.getPointAmount();
            }
        }

        //抵扣金豆 added by tim peng 2017-4-16
        //实际成交金额= 订单金额 -金豆金额
        if (offsetAmount.compareTo(BigDecimal.ZERO) == 1) {
            dealAmount1 = dealAmount1.subtract(offsetAmount);
            dealAmount2 = dealAmount2.subtract(offsetAmount);
        }


        DataResult dataResult = HttpUtil.httpGet(ProConstants.getAdminIDByUserID + dealDto.getUserID(), restTemplate);
        if (dataResult.getIsSuccess() == 0) {
            throw new ServiceException("调用base服务查询adminID失败", RestConst.ErrorCode.SERVICE_FAIL);
        }
        Map<String, Object> map = (Map<String, Object>) dataResult.getData();
        dealDto.setUserTele(map.get("mobile").toString());
        dealDto.setUserType(Integer.parseInt(map.get("type").toString()));
        dealDto.setAdminID(map.get("adminID").toString());
        dealDto.setPayNo(payNO);

        //丝绸之路满10本需要计算抵扣金豆 added by pengzh 2017-4-26
        if (offsetQty.compareTo(BigDecimal.ZERO) == 1 && silkPrice.compareTo(BigDecimal.ZERO) == 1) {
            dealAmount3 = dealAmount3.subtract(offsetAmount);
            dealQty = dealAmount3.divide(silkPrice, BigDecimal.ROUND_FLOOR).intValue();
        }
        //丝绸之路满10本
        if (dealQty >= 10) {
            dealDto.setType(2);
            dealDto.setQty(dealQty);
            dealDto.setAmount(dealAmount3);


            DataResult result1 = HttpUtil.httpPost(ProConstants.setUserGolden, dealDto, restTemplate);
            if (result1.getIsSuccess() == 0) {
                throw new ServiceException("调用point服务生成金豆失败", RestConst.ErrorCode.SERVICE_FAIL);
            }
        }
        int currunPrice = dealAmount1.compareTo(new BigDecimal(getConfigBuyAmount()));
        //珠宝商品>=3000
        if (currunPrice == 0 || currunPrice == 1) {
            dealDto.setType(1);
            dealDto.setAmount(dealAmount1);
            DataResult result2 = HttpUtil.httpPost(ProConstants.setUserGolden, dealDto, restTemplate);
            if (result2.getIsSuccess() == 0) {
                throw new ServiceException("调用point服务生成金豆失败", RestConst.ErrorCode.SERVICE_FAIL);
            }
        }

        int rr = dealAmount2.compareTo(BigDecimal.ZERO);
        if (rr == 1) {
            dealDto.setAmount(dealAmount2);
            DataResult result = HttpUtil.httpPost(ProConstants.setCommision, dealDto, restTemplate);
            if (result.getIsSuccess() == 0) {
                throw new ServiceException("调用point服务生成佣金失败", RestConst.ErrorCode.SERVICE_FAIL);
            }
        }

        //抵扣金豆 added by tim peng 2017-4-6
        if (offsetQty.compareTo(BigDecimal.ZERO) == 1) {
            Map<String, Object> para = new HashMap<String, Object>();
            para.put("amount", offsetAmount);

            para.put("point", offsetQty);
            para.put("userID", dealDto.getUserID());
            para.put("payNo", dealDto.getPayNo());

            //改为提交订单时抵扣 2017-5-12
//            DataResult result = HttpUtil.httpPost(ProConstants.setUseGolden, para, DataResult.class);
//            if (result.getIsSuccess() == 0) {
//                throw new ServiceException("调用point服务抵扣金豆失败,message=" + result.getErrorDesc(), RestConst.ErrorCode.SERVICE_FAIL);
//            }
        }


        return "success";
    }
    //付款完成生成金豆

    /**
     * add 后台返回查询订单编号
     * 其本人帐号和下级会员每购买一本丝绸之路产品，即送0.1颗金豆
     *
     * @param payNO
     * @return
     */
    private Object setPointV2(String payNO) {

        List<OrderInfo> infoList = orderInfoMapper.selectByPayNo(payNO);
        int dealQty = 0;
        BigDecimal dealAmount1 = BigDecimal.ZERO; //用于计算金豆
        BigDecimal dealAmount2 = BigDecimal.ZERO;  //用于计算佣金
        BigDecimal dealAmount3 = BigDecimal.ZERO;  //计算丝绸之路产品的佣金

        DealDto dealDto = null;

        BigDecimal offsetQty = BigDecimal.ZERO;  //抵扣金豆数量
        BigDecimal offsetAmount = BigDecimal.ZERO;  //抵扣金豆金额
        BigDecimal silkPrice = BigDecimal.ZERO;  //丝绸之路产品price

        String userId = null;
        String userManagerId = null;

        for (OrderInfo orderInfo : infoList) {
            List<OrderItem> itemList = orderItemMapper.selectByOrderID(orderInfo.getOrderID());
            for (OrderItem orderItem : itemList) {
                if (getGoldenGoodsID().equals(orderItem.getGoodsID().toString())) {
                    dealQty += orderItem.getQty();
                    //计算丝绸之路产品的无佣金 2017-4-26
                    dealAmount3 = dealAmount3.add(orderItem.getAmount());
                    silkPrice = orderItem.getRetailPrice();
                    //dealAmount2 = dealAmount2.add(orderItem.getAmount());

                }
                GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(orderItem.getGoodsID());
                if (goodsInfo.getClassifyID().equals(getGoldenClassifyID())) {
                    dealAmount1 = dealAmount1.add(orderItem.getAmount());
                    dealAmount2 = dealAmount2.add(orderItem.getAmount());
                }
            }

            if (dealDto == null) {

                dealDto = new DealDto();
                dealDto.setSubbranchId(orderInfo.getSubbranchID());//支行ID
                dealDto.setBranchId(orderInfo.getBranchID());//分行ID
                dealDto.setTwoLevelBranchId(orderInfo.getTwoLevelBranchID());//二级分行ID
                dealDto.setManagerID(orderInfo.getSalesManagerID().toString());
                //dealDto.setUserID(orderInfo.getUserID().toString());
                //dealDto.setUserName(orderInfo.getUserName());

                // add orderNo
                if (dealDto.getOrderNOS() == null || dealDto.getOrderNOS().size() == 0) {
                    List<String> orders = new ArrayList<>();
                    orders.add(orderInfo.getOrderNO());
                    dealDto.setOrderNOS(orders);
                } else {
                    List<String> orders = dealDto.getOrderNOS();
                    orders.add(orderInfo.getOrderNO());
                    dealDto.setOrderNOS(orders);
                }

                //added companyid , by tim peng 2017-4-7
                UserInfoForOrderDto userInfoForOrderDto = (UserInfoForOrderDto) getUserInfoForOrder(orderInfo.getUserID());
                if (userInfoForOrderDto != null) {
                    dealDto.setCompanyID(userInfoForOrderDto.getCompanyID());
                }
                //获取理财经理id 和用户名称
                //dealDto.setUserID(orderInfo.getSalesManagerID().toString());
                //dealDto.setUserName(orderInfo.getUserName());
                userId = orderInfo.getUserID() + "";
                userManagerId = orderInfo.getSalesManagerID() + "";
            }


            if (orderInfo.getPointQty() != null) {
                offsetQty = orderInfo.getPointQty();
                offsetAmount = orderInfo.getPointAmount();
            }
        }

        //抵扣金豆 added by tim peng 2017-4-16
        //实际成交金额= 订单金额 -金豆金额
        if (offsetAmount.compareTo(BigDecimal.ZERO) == 1) {
            dealAmount1 = dealAmount1.subtract(offsetAmount);
            dealAmount2 = dealAmount2.subtract(offsetAmount);
        }
        //丝绸之路满10本需要计算抵扣金豆 added by pengzh 2017-4-26
        dealDto.setUserID(userId);
        if (offsetQty.compareTo(BigDecimal.ZERO) == 1 && silkPrice.compareTo(BigDecimal.ZERO) == 1) {
            dealAmount3 = dealAmount3.subtract(offsetAmount);
            dealQty = dealAmount3.divide(silkPrice, BigDecimal.ROUND_FLOOR).intValue();
            //如果理财经理为null则不发送
            if (StringUtils.isNotEmpty(userManagerId)) {
                dealDto.setUserID(userManagerId);
            } else {
                logger.info("调用point服务获取用户理财经理不保存payNO:" + payNO);
                return "success";
            }
        } else if (silkPrice.compareTo(BigDecimal.ZERO) == 1) {
            if (StringUtils.isNotEmpty(userManagerId)) {
                dealDto.setUserID(userManagerId);
            } else {
                logger.info("调用point服务获取用户理财经理不保存payNO:" + payNO);
                return "success";
            }
        }

        DataResult dataResult = HttpUtil.httpGet(ProConstants.getUserByID + dealDto.getUserID(), restTemplate);
        if (dataResult.getIsSuccess() == 0) {
            logger.error("调用base服务查询adminID失败", RestConst.ErrorCode.SERVICE_FAIL);
        } else {
            Map<String, Object> map = (Map<String, Object>) dataResult.getData();
            if (map != null && map.containsKey("mobile") && map.get("mobile") != null) {
                dealDto.setUserTele(map.get("mobile") + "");
            }
            if (map != null && map.containsKey("name") && map.get("name") != null) {
                dealDto.setUserName(map.get("name") + "");
            }
        }
        dealDto.setPayNo(payNO);

        if (dealQty != 0) {
            dealDto.setType(2);
            dealDto.setQty(dealQty);
            dealDto.setAmount(dealAmount3);
            //理财经理版，其本人帐号和下级会员每购买一本丝绸之路产品，即送0.1颗金豆。不参与一次性买10本或一天累计购买10本送一颗。
            BigDecimal point = new BigDecimal(Double.valueOf("0.1"));
            dealDto.setPoint(point.multiply(new BigDecimal(dealQty)));
            DataResult result1 = HttpUtil.httpPost(ProConstants.setUserGolden, dealDto, restTemplate);
            if (result1.getIsSuccess() == 0) {
                logger.error("调用point服务生成金豆失败", RestConst.ErrorCode.SERVICE_FAIL);
            }
        }


        int currunPrice = dealAmount1.compareTo(new BigDecimal(getConfigBuyAmount()));
        //珠宝商品>=3000
        if (currunPrice >= 0) {
            dealDto.setType(1);
            dealDto.setAmount(dealAmount1);
            DataResult result2 = HttpUtil.httpPost(ProConstants.setUserGolden, dealDto, restTemplate);
            if (result2.getIsSuccess() == 0) {
                logger.error("调用point服务生成金豆失败,para=" + dealDto);
            }
        }
        int rr = dealAmount2.compareTo(BigDecimal.ZERO);
        if (rr == 1) {
            dealDto.setAmount(dealAmount2);
            DataResult result = HttpUtil.httpPost(ProConstants.setCommision, dealDto, restTemplate);
            if (result.getIsSuccess() == 0) {
                //throw new ServiceException("调用point服务生成佣金失败", RestConst.ErrorCode.SERVICE_FAIL);
                logger.error("调用point服务生成金豆失败,para=" + dealDto);
            }
        }

        return "success";
    }


    public Object getAuditCountByCompanyID(Long companyID) {
        if (isOpenGoldPoint()) {
            //DataResult result = HttpUtil.httpGet(ProConstants.getPointAuditCount, DataResult.class);
            //前后版本兼容 add peng 2017-8-1
            String url = ProConstants.getPointAuditCount;
//            // 正式环境放开
//            if (SystemContext.getRequest() != null && SystemContext.getRequest().getHeaders("ver") != null) {
//                url = ProConstants.getPointAuditCount2;
//            }
            DataResult result = HttpUtil.httpGet(url, restTemplate);
            if (result.getIsSuccess() == 1) {
                return (Map<String, Object>) result.getData();
            }
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("withDrawCashAuditQty", "0");
        map.put("withDrawGoldAuditQty", "0");
        return map;
    }

    private int getConfigBuyAmount() {
        //return 3000;
        return Integer.parseInt(getBuyAmount());
    }

    //create by zll 抛转以前的order_info中的address信息
    public Object updateOrderOldAddressInfo() {
        List<Long> addressIdList = orderInfoMapper.getAllUserAddress();
        System.out.println("开始调用远程");
        DataResult dataResult = HttpUtil.httpPost(ProConstants.BASE + "/userinfo/addressInfoMap", null, restTemplate);
        Map<Long, Map<String, Object>> userInfoMap = (Map<Long, Map<String, Object>>) dataResult.getData();
        System.out.println("远程调用结束,返回的map大小是:" + userInfoMap.size());
        List<OrderInfo> list = orderInfoMapper.getOrderInfoNoAddress();
        List<OrderInfo> errorList = new ArrayList<>();
        int i = 0;
        int errorData = 0;
        for (OrderInfo orderInfo : list) {
            Map<String, Object> addressMap = userInfoMap.get(orderInfo.getAddressID());
            if (addressMap != null) {
                orderInfo.setReceiverName((String) addressMap.get("contacts"));
                orderInfo.setReceiverPhone((String) addressMap.get("contactPhone"));
                orderInfo.setReceiverAddress((String) addressMap.get("address"));
                orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
                i++;
            } else {
                errorData++;
            }
        }
        int account = i + errorData;
        return "更新数据:" + i + "--错误数据" + errorData + "--共" + account;
    }


    /**
     * @param payNO
     * @return
     * @throws Exception
     */
    public Object selectOrderByPayNO(String payNO) throws Exception {

        List<OrderInfo> orderInfoList = orderInfoMapper.selectByPayNo(payNO);
        if (orderInfoList == null || orderInfoList.isEmpty()) {
            return null;
        }
        Long orderID = orderInfoList.get(0).getOrderID();

        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderID);
        OrderLogistics orderLogistics = new OrderLogistics();
        Map<String, Object> traceabilityObject = new HashMap<>();
        Map<String, String> receiverMap = new HashMap<>();
        orderLogistics = selectLogisticByOrderID(orderID);
        receiverMap = getAddressInfo(orderInfo);
        Long deptID = 0L;
        if (!Objects.equal(orderInfo.getSubbranchID(), 0L)) {
            deptID = orderInfo.getSubbranchID();
        } else if (!Objects.equal(orderInfo.getTwoLevelBranchID(), 0L)) {
            deptID = orderInfo.getTwoLevelBranchID();
        } else if (!Objects.equal(orderInfo.getBranchID(), 0L)) {
            deptID = orderInfo.getBranchID();
        }
        String exSql = orderInfo.getUserID() + "/" + (orderInfo.getSalesManagerID() == null ? 0L : orderInfo.getSalesManagerID()) + "/" + deptID;
        DataResult result = HttpUtil.httpGet(ProConstants.getTraceability + exSql, restTemplate);
        if (result.getIsSuccess() == 1) {
            traceabilityObject = (Map<String, Object>) result.getData();
        } else {
            System.out.print("-----调用base服务查询用户溯源信息失败-----");
        }

        OrderDto orderDto = new OrderDto();
        orderDto.setOrderInfo(orderInfo);
        orderDto.setTraceabilityObject(traceabilityObject);
        orderDto.setOrderLogistics(orderLogistics);
        orderDto.setReceiver(receiverMap);
        List<OrderItemMoreDto> moreDtoList = new ArrayList<>();
        List<OrderItem> itemList = orderItemMapper.selectByOrderID(orderID);
        for (OrderItem item : itemList) {
            OrderItemMoreDto moreDto = new OrderItemMoreDto();
            BeanUtils.copyProperties(moreDto, item);
            GoodsSku goodsSku = goodsSkuMapper.selectByPrimaryKey(item.getSkuID());
            if (goodsSku == null) {
                moreDto.setInventory(0);
            } else {
                moreDto.setInventory(goodsSku.getInventory());
            }
            moreDtoList.add(moreDto);
        }
        orderDto.setItemList(moreDtoList);
        return orderDto;
    }


    /*****************************************
     * 跟ERP对接
     **********************************************************/
    public boolean sendForErp(List<OrderInfo> infoList, String orderNo) {
        try {
            logger.info("开始抛转ERP信息");
            //对接erp信息 create by zll
            /*List<OrderInfo> selfInfoList = new ArrayList<>();
            List<OrderInfo> otherInfoList = new ArrayList<>();
            for (OrderInfo info : infoList) {
                //getSelfCompanyId
                if (CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SELFCOMPANYID.getCode()).equals(info.getSellerID().toString())) {
                    logger.info("自营");
                    selfInfoList.add(info);
                } else {
                    otherInfoList.add(info);
                }
            }
            if (selfInfoList.size() != 0) {
                List<OrderErpVo> list = getErpVoInfo(selfInfoList);
                // getAddSelfOrder == getSecretKey
                ResultData res = getExchangeData(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ADDSELFORDER.getCode()), list, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SECRETKEY.getCode()), 1);
                if (!"1".equals(res.getCode())) {
                    logger.info(res.getMessage() + ":" + res.getCode());
                    return false;
                }
            }
            if (otherInfoList.size() != 0) {
                System.out.println("准备调通代销接口");
                List<OrderErpAccessVo> list = getErpVoAccessInfo(otherInfoList);
                //getAddOtherOrder
                logger.info(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ADDOTHERORDER.getCode()) + "!!!!!!!");
                //getAddOtherOrder == getSecretKey
                ResultData resOther = getExchangeData(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ADDOTHERORDER.getCode()), list, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SECRETKEY.getCode()), 2);
                if (!"1".equals(resOther.getCode())) {
                    System.out.println(resOther.getMessage() + ":" + resOther.getCode());
                    return false;
                }
            }*/

            //品牌公司都抛砖到自营公司
            if (infoList.size() != 0) {
                List<OrderErpVo> list = getErpVoInfo(infoList);

                System.out.println("accountCode-==========" + list.get(0).getAccountCode());
                // getAddSelfOrder == getSecretKey
                ResultData res = getExchangeData(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ADDSELFORDER.getCode()), list, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SECRETKEY.getCode()), 1);
                if (!"1".equals(res.getCode())) {
                    logger.info(res.getMessage() + ":" + res.getCode());
                    return false;
                }
            }
            logger.info("抛转ERP信息成功");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    /*****************************************
     * 线下订单跟ERP对接
     **********************************************************/
    public boolean offlineSendForErp(OrderInfo info) {
        logger.info("开始抛转ERP信息");
        //对接erp信息 create by zll
       /* OrderInfo selfInfo = null;
        OrderInfo otherInfo = null;
        //getSelfCompanyId
        if (CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SELFCOMPANYID.getCode()).equals(info.getSellerID().toString())) {
            System.out.println("自营");
            selfInfo = info;
        } else {
            otherInfo = info;
        }

        try {
            if (selfInfo != null) {
                List<OrderErpVo> list = getOfflineErpVoInfo(selfInfo);
                // getAddSelfOrder == getSecretKey
                ResultData res = getExchangeData(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ADDSELFORDER.getCode()), list, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SECRETKEY.getCode()), 1);
                if (!"1".equals(res.getCode())) {
                    logger.info(res.getMessage() + ":" + res.getCode());
                    return false;
                }
            }
            if (otherInfo != null) {
                System.out.println("准备调通代销接口");
                List<OrderErpAccessVo> list = getOfflineErpVoAccessInfo(otherInfo);
                //getAddOtherOrder
                System.out.println(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ADDOTHERORDER.getCode()) + "!!!!!!!");
                //getAddOtherOrder == getSecretKey
                ResultData resOther = getExchangeData(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ADDOTHERORDER.getCode()), list, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SECRETKEY.getCode()), 2);
                if (!"1".equals(resOther.getCode())) {
                    System.out.println(resOther.getMessage() + ":" + resOther.getCode());
                    return false;
                }
            }*/
        try {
            //品牌公司都为自营订单
            if (info != null) {
                List<OrderErpVo> list = getOfflineErpVoInfo(info);
                // getAddSelfOrder == getSecretKey
                ResultData res = getExchangeData(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ADDSELFORDER.getCode()), list, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SECRETKEY.getCode()), 1);
                if (!"1".equals(res.getCode())) {
                    logger.info(res.getMessage() + ":" + res.getCode());
                    return false;
                }
            }
            logger.info("抛转ERP信息成功");
        } catch (Exception e) {
            logger.error("抛转ERP信息异常,orderNo:" + info.getOrderNO() + " error:" + e.getMessage());
            return false;
        }
        return true;

    }


    /**
     * 调起erp接口的远程工具类
     *
     * @param url
     * @param param     传递的参数
     * @param secretKey 头文件中的key
     * @return
     */
    public ResultData getExchangeData(String url, Object param, String secretKey, int type) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        MediaType mediaType = new MediaType("application", "json", Charsets.UTF_8);
        headers.setContentType(mediaType);
        headers.set("secretKey", secretKey);
        System.out.println(JSONArray.fromObject(param).toString());
        String jsonData = "";
        jsonData = JSONArray.fromObject(param).toString();
        RestTemplate ts = new RestTemplate();
//        HttpEntity<String> entity = new HttpEntity<String>(JSONArray.fromObject(param).toString(), headers);
        HttpEntity<String> entity = new HttpEntity<String>(jsonData, headers);
        ResponseEntity<ResultData> result = ts.exchange(url, HttpMethod.POST, entity, ResultData.class, "");
        ResultData res = result.getBody();
        return res;
    }


    /**
     * 调起erp接口的远程工具类
     *
     * @param url
     * @param param     传递的参数
     * @param secretKey 头文件中的key
     * @return
     */
    public ResultData getExchangeDataObject(String url, Object param, String secretKey, int type) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        MediaType mediaType = new MediaType("application", "json", Charsets.UTF_8);
        headers.setContentType(mediaType);
        headers.set("secretKey", secretKey);
        String jsonData = "";
        jsonData = JSONObject.fromObject(param).toString();
        RestTemplate ts = new RestTemplate();
//        HttpEntity<String> entity = new HttpEntity<String>(JSONArray.fromObject(param).toString(), headers);
        HttpEntity<String> entity = new HttpEntity<String>(jsonData, headers);
        ResponseEntity<ResultData> result = ts.exchange(url, HttpMethod.POST, entity, ResultData.class, "");
        ResultData res = result.getBody();
        return res;
    }

    /**
     * 调起erp接口的远程工具类
     *
     * @param url
     * @param param     传递的参数
     * @param secretKey 头文件中的key
     * @return
     */
    public ResultData getExchangeDataGET(String url, Object param, String secretKey) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        MediaType mediaType = new MediaType("application", "json", Charsets.UTF_8);
        headers.setContentType(mediaType);
        headers.set("secretKey", secretKey);

        RestTemplate ts = new RestTemplate();
        HttpEntity<String> entity = new HttpEntity<String>("", headers);
        ResponseEntity<ResultData> result = ts.exchange(url, HttpMethod.GET, entity, ResultData.class, "");
        ResultData res = result.getBody();
        return res;
    }

    /**
     * 得到erp对接的所有信息 -->自营订单
     *
     * @param infoList
     * @return
     */
    public List<OrderErpVo> getErpVoInfo(List<OrderInfo> infoList) {
        List<OrderErpVo> list = new ArrayList<>();
        for (OrderInfo info : infoList) {
            //getAccountCode
            OrderErpVo vo = this.getOrderErpVo(info, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ACCOUNTCODE.getCode()));
            list.add(vo);
        }
        return list;
    }


    /**
     * 线下订单得到erp对接的所有信息 -->自营订单
     *
     * @param info
     * @return
     */
    public List<OrderErpVo> getOfflineErpVoInfo(OrderInfo info) {
        List<OrderErpVo> list = new ArrayList<>();
        //getAccountCode
        OrderErpVo vo = this.getOfflineOrderErpVo(info, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ACCOUNTCODE.getCode()));
        list.add(vo);
        return list;
    }


    /**
     * 线下代销单的erp对接信息
     *
     * @param info
     * @return
     */
    public List<OrderErpAccessVo> getOfflineErpVoAccessInfo(OrderInfo info) {
        List<OrderErpAccessVo> list = new ArrayList<>();
        OrderErpAccessVo orderErpAccessVo = new OrderErpAccessVo();
        //getAccountElseCode()
        OrderErpVo vo = this.getOfflineOrderErpVo(info, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ACCOUNTELSECODE.getCode()));
        orderErpAccessVo.setOrder(vo);
        AccessPurchaseDto accessPurchaseDto = new AccessPurchaseDto();
        SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd");
        try {
            accessPurchaseDto.setAmount(info.getAmount() + "");
            accessPurchaseDto.setBiz_Date(System.currentTimeMillis() / 1000 + "000");
            accessPurchaseDto.setQty(info.getqty() + "");
            //getAccountElseCode()
            accessPurchaseDto.setCompCode(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.ACCOUNTELSECODE.getCode()));
            accessPurchaseDto.setRemark("");
            accessPurchaseDto.setClientID(info.getSellerID() + "");
            accessPurchaseDto.setClientName(info.getSellerName());
            accessPurchaseDto.setTotalWeight("-1");
        } catch (Exception e) {
            throw new ServiceException("公司发票必须填写发票抬头", RestConst.ErrorCode.FORM_FAIL);
        }
        List<AccessPurchaseDetailDto> accessPurchaseDetailDtoList = this.getPpnDetailList(info);
        accessPurchaseDto.setPpnDetail(accessPurchaseDetailDtoList);
        orderErpAccessVo.setPurchase(accessPurchaseDto);
        list.add(orderErpAccessVo);
        return list;
    }


    /**
     * 不论是自营还是代销 都需要主订单以及明细信息
     *
     * @param info
     * @return
     */
    public OrderErpVo getOrderErpVo(OrderInfo info, String accountCode) {
        OrderErpVo vo = new OrderErpVo();
        vo.setPayNO(info.getPayNo());
        vo.setAccountCode(accountCode);
        List<OrderInfoPay> payList = new ArrayList<>();
        //String payID, String orderID, Integer payMode, BigDecimal amount, String accountID
        // b1.subtract(b2).doubleValue();
        BigDecimal amou = info.getAmount();
        if ("1".equals(info.getCouponType())) {
            if (info.getPointAmount() != null && info.getPointAmount().intValue() != 0) {
                OrderInfoPay orderPayPoint = new OrderInfoPay("", info.getOrderID() + "", 20, info.getPointAmount(), "", info.getPayNo());
                payList.add(orderPayPoint);
            }
        } else if ("2".equals(info.getCouponType())) {

        }
        int payType = info.getPayType();
        if (info.getPayType() != null) {
            if (info.getPayType().intValue() == 4 || info.getPayType() == 1) {
                payType = 1;
            } else if (info.getPayType() == 2 || info.getPayType() == 5) {
                payType = 2;
            }
        }
        OrderInfoPay orderPay = new OrderInfoPay("", info.getOrderID() + "", payType, info.getAmount(), "", info.getPayNo());
        payList.add(orderPay);
        vo.setPays(payList);
        vo.setItems(this.getOrderItemInfoErpInfo(info)); //得到item的list
        //得到orderInfoErp中的信息
        vo.setOrderNO(info.getOrderNO() + "");
        vo.setOrderID(info.getOrderID() + "");
        vo.setDownTime(info.getAddTime());
        String url = "";
        if (info.getSalesManagerID() == null || info.getSalesManagerID() == 0) {
            url = ProConstants.getSalesManagerOrgInfoBuyer + 1 + "/" + info.getUserID();
        } else {
            url = ProConstants.getSalesManagerOrgInfoBuyer + info.getSalesManagerID() + "/" + info.getUserID();
        }
        DataResult result = HttpUtil.httpGet(url, restTemplate);
        if (result.getIsSuccess() == 1) {
            Map<String, Object> mapResult = (Map<String, Object>) result.getData();
            vo.setSaleUnit((String) mapResult.get("orgId"));
            vo.setSaleUnitName((String) mapResult.get("orgName"));
            vo.setBusinessUser((String) mapResult.get("businessUserId"));
            vo.setBusinessUserName((String) mapResult.get("businessUserName"));
            vo.setBuyNumber((String) mapResult.get("buyNumber"));
        }
        vo.setBuyUserName(info.getUserName());
        vo.setBuyID(info.getUserID() + "");
        vo.setQty(info.getqty());


        if (!Objects.equal(info.getCouponType(), "1")) {
            vo.setCostPrice(BigDecimalUtil.add(info.getAmount(), info.getPointAmount()));//原价
            vo.setDiscountMoney(info.getPointAmount());//优惠的数量
        } else {
            vo.setCostPrice(info.getAmount());//金豆优惠
            vo.setDiscountMoney(new BigDecimal(0));//优惠的数量
        }
        vo.setAmount(info.getAmount());//实际价格

        vo.setPayType(1);
        if (info.getInvoices() == 1 || info.getInvoices() == 2) {
            vo.setInvoices(2);
        } else {
            vo.setInvoices(1);
        }
        vo.setInvoicesHead(info.getInvoicesHead() == null ? "" : info.getInvoicesHead());
        vo.setInvoicesNO(info.getInvoicesNO() == null ? "" : info.getInvoicesNO());
        vo.setReceiveUser(info.getUserID() + "");
        vo.setReceiveUserName(info.getReceiverName());
        vo.setReceiveUserPhone(info.getReceiverPhone());
        vo.setReceiveAddress(info.getReceiverAddress());
        OrderAddress orderAddress = orderAddressMapper.selectByOrderId(info.getOrderID());
        if (orderAddress != null) {
            vo.setReceiveProvince(orderAddress.getProvince());
            vo.setReceiveCity(orderAddress.getCity());
            vo.setReceiveDistrict(orderAddress.getDistrict());
        }
        vo.setMemo("");
        vo.setClientID(info.getSellerID() + "");
        vo.setClientName(info.getSellerName());
        vo.setPayTime(System.currentTimeMillis());
        vo.setType(info.getType());
        return vo;
    }


    /**
     * 线下支付 不论是自营还是代销 都需要主订单以及明细信息
     *
     * @param info
     * @return
     */
    public OrderErpVo getOfflineOrderErpVo(OrderInfo info, String accountCode) {
        OrderErpVo vo = new OrderErpVo();
        vo.setPayNO(info.getPayNo() == null ? "" : info.getPayNo());
        vo.setAccountCode(accountCode);
        List<OrderInfoPay> payList = new ArrayList<>();

        if ("1".equals(info.getCouponType())) {
            if (info.getPointAmount() != null && info.getPointAmount().intValue() != 0) {
                OrderInfoPay orderPayPoint = new OrderInfoPay("", info.getOrderID() + "", 20, info.getPointAmount(), "", info.getPayNo());
                payList.add(orderPayPoint);
            }
        } else if ("2".equals(info.getCouponType())) {

        }
        ////支付方式(0现金支付1微信支付2建行支付3支付宝4银联支付5银行转账20金豆21现金券99其他
        int payType = info.getPayType();
        if (info.getPayType() != null) {
            if (info.getPayType().intValue() == 4 || info.getPayType() == 1) {
                payType = 1;
            } else if (info.getPayType() == 2 || info.getPayType() == 5) {
                payType = 2;
            } else if (info.getPayType() == 11) {
                payType = 0;
            } else if (info.getPayType() == 13) {
                payType = 4;
            } else if (info.getPayType() == 12) {
                payType = 5;
            } else if (info.getPayType() == 99) {
                payType = 99;
            }
        }
        OrderInfoPay orderPay = new OrderInfoPay("", info.getOrderID() + "", payType, info.getAmount(), "", "");
        payList.add(orderPay);
        vo.setPays(payList);
        vo.setItems(this.getOrderItemInfoErpInfo(info)); //得到item的list
        //得到orderInfoErp中的信息
        vo.setOrderNO(info.getOrderNO() + "");
        vo.setOrderID(info.getOrderID() + "");
        vo.setDownTime(info.getAddTime());
        String url = "";
        if (info.getSalesManagerID() == null || info.getSalesManagerID() == 0) {
            url = ProConstants.getSalesManagerOrgInfoBuyer + 1 + "/" + info.getUserID();
        } else {
            url = ProConstants.getSalesManagerOrgInfoBuyer + info.getSalesManagerID() + "/" + info.getUserID();
        }
        DataResult result = HttpUtil.httpGet(url, restTemplate);
        if (result.getIsSuccess() == 1) {
            Map<String, Object> mapResult = (Map<String, Object>) result.getData();
            vo.setSaleUnit((String) mapResult.get("orgId"));
            vo.setSaleUnitName((String) mapResult.get("orgName"));
            vo.setBusinessUser((String) mapResult.get("businessUserId"));
            vo.setBusinessUserName((String) mapResult.get("businessUserName"));
            vo.setBuyNumber((String) mapResult.get("buyNumber"));
        }
        vo.setBuyUserName(info.getUserName());
        vo.setBuyID(info.getUserID() + "");
        vo.setQty(info.getqty());

        if (!Objects.equal(info.getCouponType(), "1")) {
            vo.setCostPrice(BigDecimalUtil.add(info.getAmount(), info.getPointAmount()));//原价
            vo.setDiscountMoney(info.getPointAmount());//优惠的数量
        } else {
            vo.setCostPrice(info.getAmount());//金豆优惠
            vo.setDiscountMoney(new BigDecimal(0));//优惠的数量
        }
        vo.setAmount(info.getAmount());//实际价格

        vo.setPayType(2);
        if (info.getInvoices() == 1 || info.getInvoices() == 2) {
            vo.setInvoices(2);
        } else {
            vo.setInvoices(1);
        }
        vo.setInvoicesHead(info.getInvoicesHead() == null ? "" : info.getInvoicesHead());
        vo.setInvoicesNO(info.getInvoicesNO() == null ? "" : info.getInvoicesNO());
        vo.setReceiveUser(info.getUserID() + "");
        vo.setReceiveUserName(info.getReceiverName());
        vo.setReceiveUserPhone(info.getReceiverPhone());
        vo.setReceiveAddress(info.getReceiverAddress());
        OrderAddress orderAddress = orderAddressMapper.selectByOrderId(info.getOrderID());
        if (orderAddress != null) {
            vo.setReceiveProvince(orderAddress.getProvince());
            vo.setReceiveCity(orderAddress.getCity());
            vo.setReceiveDistrict(orderAddress.getDistrict());
        }
        vo.setMemo("");
        vo.setClientID(info.getSellerID() + "");
        vo.setClientName(info.getSellerName());
        vo.setPayTime(System.currentTimeMillis());
        vo.setType(info.getType());
        return vo;
    }


    /**
     * 自营商品的ERP对接明细信息
     *
     * @param info
     * @return
     */
    public List<OrderItemErp> getOrderItemInfoErpInfo(OrderInfo info) {
        List<OrderItem> list = orderItemMapper.selectByOrderID(info.getOrderID());
        List<OrderItemErp> result = new ArrayList<>();
        for (OrderItem item : list) {
            OrderItemErp itemErp = new OrderItemErp();
            itemErp.setItemID(item.getItemID() + "");
            itemErp.setOrderID(info.getOrderID() + "");
            itemErp.setProductName(item.getGoodsName());
            //getImageService
            itemErp.setPicture(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.IMAGESERVICE.getCode()) + item.getGoodsImg()); //这里的路径是要处理一下
            itemErp.setSku(item.getGoodsSku());
            itemErp.setRetailPrice(item.getPrice());//原价
            itemErp.setSalePrice(item.getRetailPrice());//实际成交价
            //折扣
            itemErp.setDiscountMoney(BigDecimalUtil.sub(itemErp.getRetailPrice(), itemErp.getSalePrice())); //优惠金额
            itemErp.setDiscount(BigDecimalUtil.div(itemErp.getSalePrice(), itemErp.getRetailPrice()));

            itemErp.setQty(item.getQty());
            itemErp.setAmount(item.getAmount());
            itemErp.setStyleNum(goodsInfoMapper.selectByPrimaryKey(item.getGoodsID()).getPrdNo()); //这里款号暂时没有
            result.add(itemErp);
        }
        return result;
    }

    public List<AccessPurchaseDetailDto> getPpnDetailList(OrderInfo info) {
        List<OrderItem> listItem = orderItemMapper.selectByOrderID(info.getOrderID());
        List<AccessPurchaseDetailDto> list = new ArrayList<>();
        for (OrderItem item : listItem) {
            AccessPurchaseDetailDto detail = new AccessPurchaseDetailDto();
            detail.setProductID(item.getItemID() + "");
            GoodsInfo goods = goodsInfoMapper.selectByPrimaryKey(item.getGoodsID());
            if (goods == null) {
                //抛出异常
            }
            List<String> classList = new ArrayList<>();
            int index = 0;
            String classId = "";
            String className = "";
            if (goods.getClassifyID() != null) {
                classList.add(goods.getClassifyID());
                classId = goods.getClassifyID();
                className = goods.getClassifyName();
                index = 1;
            }
            if (goods.getSubClassifyID() != null) {
                classList.add(goods.getSubClassifyID());
                classId = goods.getSubClassifyID();
                className = goods.getSubClassifyName();
                index = 2;
            }
            if (goods.getThreeClassifyID() != null) {
                classList.add(goods.getThreeClassifyID());
                classId = goods.getThreeClassifyID();
                className = goods.getThreeClassifyName();
                index = 3;
            }
            if (goods.getFourClassifyID() != null) {
                classList.add(goods.getFourClassifyID());
                classId = goods.getFourClassifyID();
                className = goods.getFourClassifyName();
                index = 4;
            }

            List<String> classErpList = new ArrayList<>();
            classErpList.add((String) classList.get(index - 1));
            RetateDto retateDto = new RetateDto();
            retateDto.setType("1");
            retateDto.setRelateList(classErpList);
            retateDto.setPlatform(Integer.parseInt(CommonTools.getExtString(restTemplate, "classifyType")));
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            MediaType mediaType = new MediaType("application", "json", Charsets.UTF_8);
            headers.setContentType(mediaType);
            //getSecretKey
            headers.set("secretKey", CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SECRETKEY.getCode()));
            RestTemplate ts = new RestTemplate();
            HttpEntity<RetateDto> entity = new HttpEntity<RetateDto>(retateDto, headers);
            //getClassQuery
            ResponseEntity<ResultData> result = ts.exchange(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.CLASSQUERY.getCode()), HttpMethod.POST, entity, ResultData.class, "");
            ResultData res = result.getBody();
            Map<String, String> classMap = (Map<String, String>) res.getData();
            detail.setGgtwoClass(classMap.get(classId));
            System.out.println(detail.getGgtwoClass() + "---------分类------------");
            detail.setGgtwoClassName(className);

            detail.setClientStyleNum(goods.getPrdNo() + "");
            detail.setGgprodName(goods.getName());
            String pphInfo = item.getGoodsSku();
            JSONObject json = JSONObject.fromObject(pphInfo);
            detail.setGgstyle("");
            detail.setGgstyleName(""); //款式
            detail.setFineness("");
            detail.setFinenessName("");//成色
            if (json.get("GGcolor") == null) {
                detail.setGgcolor("");
            } else {
                detail.setGgcolor(json.get("GGcolor").toString());
            }
            if (json.get("kindWater") == null) {
                detail.setKindWater("");
                detail.setKindWaterName("");
            } else {
                detail.setKindWater(json.get("kindWater").toString());
                detail.setKindWaterName(json.get("kindWater").toString());
            }
            if (json.get("GGtotalWeight") == null) {
                detail.setWeight("0");
            } else {
                detail.setWeight(json.get("GGtotalWeight").toString());
            }
            if (json.get("goldWeight") != null) {
                detail.setGoldWeight(json.get("goldWeight").toString());
            } else {
                detail.setGoldWeight("");
            }
            if (json.get("GGhandSize") != null) {
                detail.setGghandSize(json.get("GGhandSize").toString());
            } else {
                detail.setGghandSize("");
            }
            if (json.get("GGlength") != null) {
                detail.setGglength(json.get("GGlength").toString());
            } else {
                detail.setGglength("");
            }
            if (json.get("GGinnerSize") != null) {
                detail.setGginnerSize(json.get("GGinnerSize").toString());
            } else {
                detail.setGginnerSize("");
            }
            if (json.get("size") != null) {
                detail.setSize(json.get("size").toString());
            } else {
                detail.setSize("");
            }
            if (json.get("msWeight") != null) {
                detail.setMsWeight(json.get("msWeight").toString());
            } else {
                detail.setMsWeight("");
            }
            detail.setMsUnit("");
            detail.setMsUnitName("");//主石单位
            if (json.get("msColor") != null) {
                detail.setMsColor(json.get("msColor").toString());
                detail.setMsColorName(json.get("msColor").toString());
            } else {
                detail.setMsColor("");
                detail.setMsColorName("");
            }
            if (json.get("msClarity") != null) {
                detail.setMsClarity(json.get("msClarity").toString());
                detail.setMsClarityName(json.get("msClarity").toString());
            } else {
                detail.setMsClarity("");
                detail.setMsClarityName("");
            }
            if (json.get("msCut") != null) {
                detail.setMsCut(json.get("msCut").toString());
                detail.setMsCutName(json.get("msCut").toString());
            } else {
                detail.setMsCut("");
                detail.setMsCutName("");
            }
            detail.setCostPrice("0");
            detail.setGgretailMethod("1");
            detail.setGgretailMethodName("");
            detail.setGgretailPrice(item.getAmount() + "");
            detail.setGgqty(item.getQty() + "");
            //getImageService
            detail.setGgpicture(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.IMAGESERVICE.getCode()) + goods.getImg());
            detail.setGgmemo("");
            list.add(detail);
        }
        return list;
    }

    //********************erp错误数据处理*************************
    public Object updateErpErrorDataByPayNo(String payNo) {
        ErrErpOrder isExists = errErpOrderMapper.selectByPayNo(payNo);
        if (isExists == null) {
            return "0";
        }
        if (isExists != null && "1".equals(isExists.getState())) {
            return "1";
        }
        List<OrderInfo> infoList = orderInfoMapper.selectByPayNo(payNo);
        boolean isErp = sendForErp(infoList, payNo);
        if (isErp) {

            return "1";
        } else {
            ErrErpOrder errErpOrder = new ErrErpOrder();
            errErpOrder.setErrorId(IdGen.get().nextId());
            errErpOrder.setPayNo(payNo);//实际存的是payNo
            errErpOrder.setAddTime(System.currentTimeMillis());
            errErpOrder.setState("0");
            errErpOrderMapper.insertSelective(errErpOrder);
            logger.error("对接ERP信息失败,PayNo单号为" + payNo);
            return "0";
        }
    }

    /**
     * 根据orderId更新erp信息 请注意 如果成功 需要手动更改err_error表中的数据
     *
     * @param orderId
     * @return
     */
    public Object updateErpErrorDataByOderId(Long orderId) {
        OrderInfo info = orderInfoMapper.selectByPrimaryKey(orderId);
        boolean isErp = sendForErp(Lists.newArrayList(info), info.getPayNo());
        if (isErp) {
            return "1";
        } else {
            return "0";
        }
    }

    /**
     * 一次性抛转所有信息
     *
     * @return
     */
    public Object updateErpErrorData() {
        List<ErrErpOrder> list = errErpOrderMapper.selectByState();
        int count = 0;
        if (list != null) {
            for (ErrErpOrder err : list) {
                List<OrderInfo> infoList = orderInfoMapper.selectByPayNo(err.getPayNo());
                boolean isErp = sendForErp(infoList, err.getPayNo());
                if (isErp) {
                    err.setState("1");
                    err.setUpdateTime(System.currentTimeMillis());
                    errErpOrderMapper.updateByPrimaryKeySelective(err);
                } else {
                    err.setState("2");
                    err.setUpdateTime(System.currentTimeMillis());
                    logger.error("抛转订单再次失败");
                    count += 1;
                }
            }
        }
        return count;
    }


    /**
     * 得到未处理的所有的总数
     *
     * @return
     */
    public Object getErrorCount() {
        List<ErrErpOrder> list = errErpOrderMapper.selectByStateError();
        if (list == null) {
            return 0;
        } else {
            return list.size();
        }
    }


    public Object updateOldErpOrderInfo() {
        //select * from `order_info`  where amount >10 and state >2
        List<OrderInfo> list = orderInfoMapper.getOldOrderInfo();
        System.out.println(list.size());

        Map<String, String> payNoMap = new HashMap<>();
        for (OrderInfo orderInfo : list) {
            payNoMap.put(orderInfo.getPayNo(), orderInfo.getPayNo());
        }
        Iterator iter = payNoMap.values().iterator();
        int index = 0;
        while (iter.hasNext()) {
            String payNo = (String) iter.next();
            List<OrderInfo> orderInfoList = orderInfoMapper.selectByPayNo(payNo);
            boolean isErp = sendForErp(orderInfoList, payNo);
            if (isErp) {
                logger.info("对接ERP信息成功,(PayNo)单号为" + payNo);
                index += 1;
            } else {
                logger.error("抛转旧订单失败");
                return 0;
            }
        }

//        int index = 0;
//        for(OrderInfo orderInfo:list){
//
//            String payNo = orderInfo.getPayNo();
//            List<OrderInfo> orderInfoList = orderInfoMapper.selectByPayNo(payNo);
//            boolean isErp = sendForErp(orderInfoList,payNo);
//            if(isErp){
//                logger.info("对接ERP信息成功,(PayNo)单号为"+payNo);
//                index+=1;
//            }else{
//               logger.info("抛转旧订单失败");
//                return 0;
//            }
//        }
        return index;
    }

    public Object updateOldErpOrderInfoSome() {
        //select * from `order_info`  where amount >10 and state >2
        List<OrderInfo> list = orderInfoMapper.getOldThrOrderInfo();
        System.out.println(list.size());

        Map<String, String> payNoMap = new HashMap<>();
        for (OrderInfo orderInfo : list) {
            payNoMap.put(orderInfo.getPayNo(), orderInfo.getPayNo());
        }
        Iterator iter = payNoMap.values().iterator();
        int index = 0;
        while (iter.hasNext()) {
            String payNo = (String) iter.next();
            List<OrderInfo> orderInfoList = orderInfoMapper.selectByPayNo(payNo);
            boolean isErp = sendForErp(orderInfoList, payNo);
            if (isErp) {
                logger.info("对接ERP信息成功,(PayNo)单号为" + payNo);
                index += 1;
            } else {
                logger.error("抛转旧订单失败");
                return 0;
            }
        }
        return index;
    }

    /**
     * 订单支付前验证
     *
     * @param orderID
     * @return
     */
    public Object orderValid(Long orderID) {
        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderID);
        if (1 != orderInfo.getState()) {
            throw new ServiceException("订单状态有误，不能付款", RestConst.ErrorCode.DATABASE_ERROR);
        }
        List<OrderItem> itemList = orderItemMapper.selectByOrderID(orderID);
        for (OrderItem orderItem : itemList) {
            GoodsInfoWithSkuDto goodsInfoWithSkuDto = goodsInfoMapper.selectBySkuID(orderItem.getSkuID());
            if (goodsInfoWithSkuDto == null) {
                throw new ServiceException("未查到商品SKU信息", RestConst.ErrorCode.DATABASE_ERROR);
            }
            if (!goodsInfoWithSkuDto.getState().equals("Shelve")) {
                throw new ServiceException("商品已失效，不能购买", RestConst.ErrorCode.DATABASE_ERROR);
            }
           /* if (goodsInfoWithSkuDto.getInventory() < orderItem.getQty()) {
                throw new ServiceException("库存不足！" + orderItem.getGoodsName(), RestConst.ErrorCode.DATABASE_ERROR);
            }*/
        }
        if (orderInfo.getPointQty() != null
                && orderInfo.getPointQty().compareTo(BigDecimal.ZERO) == 1) {
            BigDecimal upwithdrawAvailable = getUserPointInfo(orderInfo.getUserID());
            if (orderInfo.getPointQty().compareTo(upwithdrawAvailable) == 1) {
                throw new ServiceException("您金豆不足，请重新选择", RestConst.ErrorCode.DATABASE_ERROR);
            }
        }
        return "success";
    }

    /**
     * 获取用户金豆可以余额
     *
     * @param userID
     * @return
     */
    public BigDecimal getUserPointInfo(Long userID) {
        JSONObject jsonObject = HttpUtil.httpGetJSONObject(ProConstants.getUserPointInfo + userID, restTemplate);
        //if (jsonObject.get("isSuccess") != 1) {
        if (!com.google.common.base.Objects.equal(DataUtils.getInteger(jsonObject, "isSuccess"), 1)) {
            throw new ServiceException("调用Point服务获取用户信息接口出错", RestConst.ErrorCode.SERVICE_FAIL);
        }
        Map<String, Object> map = (Map<String, Object>) jsonObject.get("data");
        Map<String, Object> userMap = (Map<String, Object>) map.get("userPoint");
        return CommonTools.getBigDecimal(userMap.get("upwithdrawAvailable"));
    }

    /**
     * 导出订单明细
     *
     * @param map
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public List<Map<String, String>> exportOrderDetail(Map<String, String> map, HttpServletRequest
            request, HttpServletResponse response) throws Exception {
        List<Map<String, String>> list = new ArrayList<>();
        try {
            map.put("companyID", String.valueOf(SystemContext.getCompanyID()));
            list = orderInfoMapper.exportOrderDetail(map);
            ExportExcel.excelWrite(map, list, ProConstants.EXPORT_ORDER_DETAIL + "_" + CommonUtils.getCurTimestamp(), request, response);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
        return list;
    }


    //获取golden config
    public boolean isOpenGoldPoint() {

        logger.info("isOpenGoldPoint url=" + ProConstants.getBizConfig + SystemContext.getCompanyID());

        try {
            DataResult result = HttpUtil.httpGet(ProConstants.getBizConfig + SystemContext.getCompanyID(), restTemplate);
            if (result.getIsSuccess() == 1) {
                String ok = (String) ((Map) result.getData()).get("isOpenGoldPoint");
                openGoldPoint = ok;
                return "1".equalsIgnoreCase(ok);
            } else {
                logger.error("isOpenGoldPoint 调用base服务失败");
            }
        } catch (Exception ex) {
            logger.error("isOpenGoldPoint 调用base服务失败", ex);
        }
        openGoldPoint = "0";
        return false;

    }

    //获取golden Erp config
    public boolean isOpenErp() {
        //if (openGoldPoint == null) {
        logger.info("isOpenErp url=" + ProConstants.getBizConfig + SystemContext.getCompanyID());
        DataResult result = HttpUtil.httpGet(ProConstants.getBizConfig + SystemContext.getCompanyID(), restTemplate);
        if (result.getIsSuccess() == 1) {
            String ok = (String) ((Map) result.getData()).get("isOpenErp");
            isOpenErp = ok;
            return "1".equalsIgnoreCase(ok);
        } else {
            logger.error("isOpenErp 调用base服务失败");
        }
        isOpenErp = "0";
        return false;
       /* } else {
           return "1".equalsIgnoreCase(isOpenErp);
        }*/
    }


    /**
     * 获取 是否启动金豆购买抵扣
     *
     * @return
     */
    private boolean isOpenPointDeduction() {
        //if (openPointDeduction == null) {
        logger.info("isOpenPointWithdraw url=" + ProConstants.getBizConfig + SystemContext.getCompanyID());
        DataResult result = HttpUtil.httpGet(ProConstants.getBizConfig + SystemContext.getCompanyID(), restTemplate);
        if (result.getIsSuccess() == 1) {
            String deduction = (String) ((Map) result.getData()).get("isOpenPointDeduction");
            openPointDeduction = deduction;
            return "1".equalsIgnoreCase(deduction);
        } else {
            logger.error("isOpenPointWithdraw 调用base服务失败");
        }
        // openPointDeduction = "0";
        return false;
        // } else {
        //      return "1".equalsIgnoreCase(openPointDeduction);
        //  }
    }

    /**
     * 获取昨天下单满10个以上会员 增送1个金豆
     *
     * @return
     */
    public Object selectYesterDayOrderUser(String _date) {
        String date = CommonUtils.formatDateTime(DateUtils.addDays(new Date(), -1), "yyyy-MM-dd");
        if (_date != null) {
            date = _date;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("goodsid", getGoldenGoodsID());
        map.put("databaseTable", databaseTableUser);
        map.put("userCount", "10");
        map.put("time", date);
        List<OrderInfo> infos = orderInfoMapper.selectYesterDayOrderUser(map);

        for (OrderInfo orderInfo : infos) {

            Map<String, Object> orderUserMap = new HashMap<>();
            orderUserMap.put("goodsid", getGoldenGoodsID());
            orderUserMap.put("userid", orderInfo.getUserID());
            orderUserMap.put("time", date);

            List<String> list = orderInfoMapper.selectOrderPresentID(orderUserMap);
            logger.info(ProConstants.orderPresentPoint + "/" + orderInfo.getUserID() + "/" + orderInfo.getqty());
            DataResult result1 = HttpUtil.httpPost(ProConstants.orderPresentPoint + "/" + orderInfo.getUserID() + "/" + orderInfo.getqty(), list, restTemplate);
            if (result1.getIsSuccess() != 1) {
                logger.error("赠送金豆失败:" + orderInfo.getUserID());
            }
        }
        return "success";
    }

    /**
     * 用户核销
     *
     * @param orderCheck
     * @return
     */
    public Object orderCheck(OrderCheckDto orderCheck) {
        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderCheck.getOrderID());
        if (orderInfo != null) {
            if (StringUtils.isNotEmpty(orderCheck.getCheckCode()) && orderCheck.getCheckCode().equals(orderInfo.getCheckCode())) {
                orderInfo.setCheckUserID(orderCheck.getUserID());
                orderInfo.setCheckUserName(orderCheck.getUserName());
                orderInfo.setCheckMemo(orderCheck.getCheckMemo());
                orderInfo.setPayType(orderCheck.getPayType());
                orderInfo.setPayTime(CommonUtils.getCurTimestamp());
                orderInfo.setState(2);
                //add by wanglq for 手续费
                //orderInfo.setTransactionFee(getTransactionFee(orderInfo.getAmount(),orderInfo.getPayType()));
                orderInfo.setOtherFee(getOtherFee());
                orderInfoMapper.updateByPrimaryKeySelective(orderInfo);

                //跟新库存 核销减少库存
                List<OrderItem> orderItemList = orderItemMapper.selectByOrderID(orderInfo.getOrderID());
                for (OrderItem item : orderItemList) {
                    boolean goodsType = goodsService.changeInventory(2, item.getGoodsID(), item.getSkuID(), item.getQty(), item.getItemID());
                    if (!goodsType) {
                        logger.error("修改库存失败:" + orderInfo.getOrderID());
                    }
                }

                commissionUserService.addCommissionV3(orderInfo);//订单核销送用佣金

                //索引
                OrderIndexOfflineDto indexOfflineDto = new OrderIndexOfflineDto();
                indexOfflineDto.setOrderID(orderInfo.getOrderID().toString());
                indexOfflineDto.setStatus(2);
                indexOfflineDto.setPayTime(orderInfo.getPayTime() == null ? "0" : orderInfo.getPayTime() + "");
                indexOfflineDto.setPayType(orderInfo.getPayType() == null ? 0 : orderInfo.getPayType());
                indexOfflineDto.setCheckInvalidTime(orderInfo.getCheckInvalidTime() == null ? "0" : orderInfo.getCheckInvalidTime() + "");
                indexOfflineDto.setOrderPayType("1");
                boolean offline = orderIndexService.updateOffline(indexOfflineDto);
                if (!offline) {
                    logger.error("修改索引失败orderid:" + orderInfo.getOrderID());
                }
                if (isOpenErp()) {
                    //erp对接 判断添加还是修改
                    if (orderInfo.getCancelUserID() == null) {
                        //订单核销推送erp新增
                        addERPOrderInfo(orderInfo);
                    } else {
                        updateERPOrderInfo(orderInfo);
                    }
                }
                return "success";
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("isSuccess", 0);
            jsonObject.put("errorDesc", "核销码不匹配请重试");
            return jsonObject;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("isSuccess", 0);
        jsonObject.put("errorDesc", "订单失效");
        return jsonObject;
    }


    /**
     * 用户撤销
     *
     * @param orderCheck
     * @return
     */
    public Object orderCheckOff(OrderCheckDto orderCheck) {
        OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderCheck.getOrderID());
        if (orderInfo != null && orderInfo.getState() == 2) {
            orderInfo.setCancelMemo(orderCheck.getCancelMemo());
            orderInfo.setCancelUserName(orderCheck.getCancelUserName());
            orderInfo.setCancelUserID(orderCheck.getCancelUserID());
            orderInfo.setCancelTime(CommonUtils.getCurTimestamp());
            orderInfo.setPayTime(0L);
            orderInfo.setPayType(0);
            orderInfo.setState(1);
            //add by wanglq for 手续费
            //orderInfo.setTransactionFee(BigDecimal.valueOf(0));
            orderInfoMapper.updateByPrimaryKeySelective(orderInfo);

            //跟新库存 回滚库存
            List<OrderItem> orderItemList = orderItemMapper.selectByOrderID(orderInfo.getOrderID());
            for (OrderItem item : orderItemList) {
                goodsService.changeInventory(4, item.getGoodsID(), item.getSkuID(), item.getQty(), item.getItemID());
            }

            //更新索引数据
            OrderIndexOfflineDto indexOfflineDto = new OrderIndexOfflineDto();
            indexOfflineDto.setOrderID(orderInfo.getOrderID().toString());
            indexOfflineDto.setStatus(1);
            indexOfflineDto.setPayTime(orderInfo.getPayTime() == null ? "0" : orderInfo.getPayTime() + "");
            indexOfflineDto.setPayType(orderInfo.getPayType() == null ? 0 : orderInfo.getPayType());
            indexOfflineDto.setCheckInvalidTime(orderInfo.getCheckInvalidTime() == null ? "0" : orderInfo.getCheckInvalidTime() + "");
            indexOfflineDto.setOrderPayType("1");
            orderIndexService.updateOffline(indexOfflineDto);
            //erp开关
            if (isOpenErp()) {
                boolean isErp = bankOfflineSendForErp(orderInfo);
                if (isErp) {
                    logger.info("对接ERP信息成功,(orderNO)单号为" + orderInfo.getOrderNO());
                } else {
                    throw new ServiceException("撤销失败!", RestConst.ErrorCode.SERVICE_FAIL);
                }
            }
        } else {
            throw new ServiceException("撤销失败!供应商已确认订单!", RestConst.ErrorCode.SERVICE_FAIL);

        }

        return "success";
    }

    /**
     * 线下修改当天订单状态改成已失效
     *
     * @return
     */
    public Object updateOrderStateOffline(String _date) {
        String date = CommonUtils.formatDateTime(new Date(), "yyyy-MM-dd");
        if (_date != null) {
            date = _date;
        }
        List<OrderInfo> list = orderInfoMapper.selectOrderStateOffline(date);
        for (OrderInfo orderInfo : list) {
            //修改es里面数据
            OrderIndexOfflineDto indexOfflineDto = new OrderIndexOfflineDto();
            indexOfflineDto.setOrderID(orderInfo.getOrderID().toString());
            indexOfflineDto.setStatus(0);
            indexOfflineDto.setPayTime(orderInfo.getPayTime() == null ? "0" : orderInfo.getPayTime() + "");
            indexOfflineDto.setPayType(orderInfo.getPayType() == null ? 0 : orderInfo.getPayType());
            indexOfflineDto.setCheckInvalidTime(orderInfo.getCheckInvalidTime() == null ? "0" : orderInfo.getCheckInvalidTime() + "");
            indexOfflineDto.setOrderPayType("1");
            orderIndexService.updateOffline(indexOfflineDto);
            //库存回滚
            List<OrderItem> itemList = orderItemMapper.selectByOrderID(orderInfo.getOrderID());
            for (OrderItem item : itemList) {
                goodsService.changeInventory(0, item.getGoodsID(), item.getSkuID(), item.getQty(), item.getItemID());
            }
        }
        orderInfoMapper.updateOrderStateOffline(date);
        return "success";
    }


    /**
     * 设置定时任务：理财经理金豆佣金
     * 默认是每天00:00,计算上一天
     *
     * @return
     */
    public Object setupCronJobOrderStateOffline() {
        //启动之前先删除
        restTemplate.delete(ProConstants.QUARTZ + "/commission/" + GROUP);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("taskId", "commission");
        map.put("time", "0 0 0 * * ?");
        map.put("jobUrl", ProConstants.BANK + "/order/orderStateOffline");
        map.put("group", GROUP);
        DataResult dataResult = HttpUtil.httpPost(ProConstants.QUARTZ, map, restTemplate);
        if (dataResult.getIsSuccess() == 0) {
            logger.error("setupCronJob ...error");
            return "error";
        }
        logger.info("setupCronJob commission...cron={}", map.get("time"));
        logger.info("setupCronJob commission...jobUrl={}", map.get("jobUrl"));
        logger.info("setupCronJob commission...success");
        return "success";
    }

  /*  public static void main(String[] agres){
        String date = CommonUtils.formatDateTime(DateUtils.addDays(new Date(), +7), "yyyy-MM-dd HH");
    System.out.println(date);
        System.out.println(getRandByNum(4));

    }*/

    /**
     * 订单核销推送erp系统
     *
     * @param orderInfo
     * @return
     */
    public boolean addERPOrderInfo(OrderInfo orderInfo) {
        if (!isOpenErp()) {
            return true;
        }
        boolean isErp = offlineSendForErp(orderInfo);
        if (isErp) {
            logger.info("对接ERP信息成功,(orderNO)单号为" + orderInfo.getOrderNO());
        } else {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("mobile", CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.TELEPHONE.getCode())); //下单人手机
            jsonObject.put("type", SmsTempEnum.ERP_EXCEPTION.getCode());//对接erp异常
            jsonObject.put("param", new String[]{"对接ERP订单信息失败:orderNO单号为" + orderInfo.getOrderNO()});
            DataResult result = HttpUtil.httpPost(ProConstants.SMS + "/notice", jsonObject, restTemplate);
            if (result.getIsSuccess() != 1) {
                logger.error("发送短信失败");
            }
            ErrErpOrder errErpOrder = new ErrErpOrder();
            errErpOrder.setErrorId(IdGen.get().nextId());
            errErpOrder.setPayNo("");//实际存的是payNo
            errErpOrder.setAddTime(System.currentTimeMillis());
            errErpOrder.setState("2");
            errErpOrderMapper.insertSelective(errErpOrder);
            logger.error("对接ERP信息失败,orderNO单号为" + orderInfo.getOrderNO());
            return false;
        }
        return true;
    }


    /**
     * 订单核销推送 erp系统 修改
     *
     * @param orderInfo
     * @return
     */
    public boolean updateERPOrderInfo(OrderInfo orderInfo) {
        if (!isOpenErp()) {
            return true;
        }
        boolean isErp = updateOfflineSendForErp(orderInfo);
        if (isErp) {
            logger.info("对接ERP信息成功,(orderNO)单号为" + orderInfo.getOrderNO());
        } else {
            throw new ServiceException("erp撤销失败!", RestConst.ErrorCode.SERVICE_FAIL);
        }
        return true;
    }

    /*****************************************
     * 线下订单跟ERP对接修改订单状态
     **********************************************************/
    public boolean updateOfflineSendForErp(OrderInfo info) {
        logger.info("开始抛转ERP信息");
        CavDto cavDto = new CavDto();
        List<OrderInfoPay> payList = new ArrayList<>();
        ////支付方式(0现金支付1微信支付2建行支付3支付宝4银联支付5银行转账20金豆21现金券99其他
        int payType = info.getPayType();
        if (info.getPayType() != null) {
            if (info.getPayType().intValue() == 4 || info.getPayType() == 1) {
                payType = 1;
            } else if (info.getPayType() == 2 || info.getPayType() == 5) {
                payType = 2;
            } else if (info.getPayType() == 11) {
                payType = 0;
            } else if (info.getPayType() == 13) {
                payType = 4;
            } else if (info.getPayType() == 12) {
                payType = 5;
            } else if (info.getPayType() == 99) {
                payType = 99;
            }
        }
        OrderInfoPay orderPay = new OrderInfoPay("", info.getOrderID() + "", payType, info.getAmount(), "", "");
        payList.add(orderPay);
        cavDto.setPays(payList);
        cavDto.setPayTime(info.getPayTime());
        cavDto.setOrderID(info.getOrderID() + "");
        try {
            if (info != null) {
                //getUpdateOtherOrderPay
                ResultData res = getExchangeDataObject(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.UPDATEOTHERORDERPAY.getCode()), cavDto, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SECRETKEY.getCode()), 1);
                if (!"1".equals(res.getCode())) {
                    logger.info(res.getMessage() + ":" + res.getCode());
                    return false;
                }
            }
        } catch (Exception e) {
            logger.error("抛转ERP信息异常,orderNo:" + info.getOrderNO() + " error" + e);
            return false;
        }
        return true;

    }


    /*****************************************
     * 线下订单跟ERP对接修改订单状态
     **********************************************************/
    public boolean bankOfflineSendForErp(OrderInfo info) {
        logger.info("开始抛转ERP信息");

        try {
            if (info != null) {
                //getBackOrderPay
                ResultData res = getExchangeDataGET(CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.BACKORDERPAY.getCode()) + "?orderNO=" + info.getOrderID(), null, CommonTools.getExtString(restTemplate, ErpInterfaceCfgEnum.SECRETKEY.getCode()));
                if (!"1".equals(res.getCode())) {
                    logger.info(res.getMessage() + ":" + res.getCode());
                    return false;
                }
            }
        } catch (Exception e) {
            logger.error("抛转ERP信息异常,orderNo:" + info.getOrderNO() + " error" + e);
            return false;
        }
        return true;

    }

    //指定送金豆商品
    public String getGoldenGoodsID() {
        return CommonTools.getExtString(restTemplate, PointCfgEnum.GOLDENGOODSID.getCode());
    }

    //短信通知开关：1/0
    public String getNoticeSMS() {
        return CommonTools.getExtString(restTemplate, "noticeSMS");
    }

    //支付抬头名称
    public String getPayTitle() {
        return CommonTools.getExtString(restTemplate, "payTitle");
    }

    //金豆配置的分类ID
    public String getGoldenClassifyID() {
        return CommonTools.getExtString(restTemplate, PointCfgEnum.GOLDENCLASSIFYID.getCode());
    }

    //买满金额送金豆
    public String getBuyAmount() {
        return CommonTools.getExtString(restTemplate, PointCfgEnum.BUYAMOUNT.getCode());
    }

    //是否测试环境支付(0/1),只需付一分钱
    public String getPaymentOnline() {
        return CommonTools.getExtString(restTemplate, "paymentOnline");
    }

    /**
     * 获取中银金行开关折扣开关
     *
     * @param
     * @return
     */

    //中银金行 折扣控制展示价格开关
    public Boolean getBocgold() {
        /*String bocgold = CommonTools.getExtString(restTemplate, "bocgold");
        return "1".equalsIgnoreCase(bocgold);*/
        return true;
    }

    public Object delAllIndex() {
        try {
            List<Long> orderIDList = orderInfoMapper.selectAllID();
            for (Long orderID : orderIDList) {
                boolean result = orderIndexService.deleteIndex(orderID);
                if (!result) {
                    throw new ServiceException("删除索引失败", RestConst.ErrorCode.SERVICE_FAIL);
                }
            }
        } catch (Exception e) {
            throw new ServiceException("删除索引失败", e);
        }
        return true;
    }

    public List<OrderInfo> selectDeptRecord(Long oID, Integer level) {
        Long startTime = DateUtil.firstDayOfMonth();
        Long endTime = DateUtil.lastDayOfMonth();
        return orderInfoMapper.selectDeptRecord(oID, level, startTime, endTime, SystemContext.getCompanyID());
    }

    public String updateDeptOrderToNewDept(Long oID, Integer level) {
        List<OrderInfo> list = selectDeptRecord(oID, level);
        for (OrderInfo orderInfo : list) {
            if (level == 1) {
                return "";
            } else if (level == 2) {
                orderInfo.setBranchID(0L);
                orderInfo.setTwoLevelBranchID(0L);
                orderInfo.setSubbranchID(0L);
            } else if (level == 3) {
                orderInfo.setTwoLevelBranchID(0L);
                orderInfo.setSubbranchID(0L);
            } else if (level == 4) {
                orderInfo.setSubbranchID(0L);
            }
            orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
        }
        return "success";
    }


    /**
     * 获取商城的机构信息 2018
     *
     * @param shopID 商城ID
     * @return 返回机构对象
     */
    public Map<String, Object> getMallInfo(Long shopID) {
        //查找商城
        DataResult result = HttpUtil.httpGet(ProConstants.BASE + "/organizational/queryOrginfo/" + shopID, restTemplate);
        if (result.getIsSuccess() == 0 || result.getData() == null) {
            throw new ServiceException("未获取到商城店铺资料");
        }
        Map<String, Object> orginfo = (Map<String, Object>) result.getData();

        return orginfo;

    }


    /**
     * 取消优惠券
     *
     * @param orderID 商城ID
     * @return 返回机构对象
     */
    public void cancelCoupon(Long orderID) {

        try {
            DataResult result = HttpUtil.httpGet(ProConstants.getUnlockCoupon + orderID, restTemplate);
            if (result.getIsSuccess() == 0 || result.getData() == null) {
                logger.error("取消优惠券调用失败，orderID=" + orderID);
            }
        } catch (Exception ex) {
            logger.error("取消优惠券调用失败", ex);
        }
    }
}
